views:

284

answers:

5

Hello everyone,

I am using VSTS 2008 + C# + .Net 2.0 to develop a Windows Forms application. In the default Form1 I have a button, and click the button will invoke another Form -- Form2.

My question is, I want to make Form2 always on the top, i.e. user must response Form2 (fill in informaiton in Form2 and close it) until the user could continue to deal with Form1. How to implement this feature?

Here is my current code.

public partial class Form1 : Form { public Form1() { InitializeComponent(); }

private void button1_Click(object sender, EventArgs e)
{
    Form2 form2 = new Form2();
    form2.Visible = true;
}

}

thanks in advance, George

+1  A: 

Hello, try this

this.TopMost = true;
mykhaylo
Sorry your solution does not work. I have added code form2.TopMost = true, but after adding the code, I can still remove Form2 aside and continue to response to Form1. Any ideas what is wrong?
George2
The best solution for one application(many forms) is ShowDialog method.
mykhaylo
+10  A: 

The best option to do exactly what you want is to make form2 a dialog box. You do this by calling its

form2.ShowDialog()

method.

Fara
+1 - George should use modal dialog, not topmost.
Mihail
Thanks Alex, your solution works!
George2
+1  A: 

Assuming that you want to prevent the user from interacting with Form1 until they're finished with Form2, you want the ShowDialog() method.

Bevan
A: 

With native .NET theres no way to put a form on top and hold it there.

Form.TopMost sets the form on top only on create. Form.ShowDialog() sets the form on top of all forms of that application, but can then be thrown backwards behind other applications as well.

I remember that we used some P/Invoke-Calls to native Win32 to handle that case, but do not remember what calls exactly. Anyway 100% were never reached, spreaded on Win2000 to WinXP nothing worked everywhere.

BeowulfOF
A: 

You can use the Win32 ::SetWindowPos() method and set the HWND hWndInsertAfter to HWND_TOPMOST so that it stays on top.

Look here for the SetWindowPos documentation: http://msdn.microsoft.com/en-us/library/ms633545(VS.85).aspx

[DllImport("user32.dll")]
static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int    cx, int cy, uint uFlags);

Here are some examples: http://www.pinvoke.net/default.aspx/user32/SetWindowPos.html

Oliver