Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make form topmost to the application only?

Tags:

c#

c#-3.0

c#-2.0

I am making excel add-in in which clicking on menu item or toolbar button, Form opened. I have set form's topmost to true but it remain topmost to all applications of windows xp. I just need to remain topmost to Microsoft Excel only.

I have choosed project in Visual Studio 2008, in Excel ->2003.

Please tell me how to do that with any way ........

like image 711
Hiren Gujarati Avatar asked Apr 10 '10 13:04

Hiren Gujarati


2 Answers

You can set your Form's owner to be the Microsoft Excel window. In Windows owned windows are always displayed above their owner. Dialogs and things like the search box in Excel are owned windows, which is what keeps them displayed above their owner.

There are a couple of ways you can set a Form's parent:

  1. The Form.Owner property (although the owner has to be another form)
  2. Use the Form.Show(IWin32Window owner) overload. (See this blog post for how translate an window handle to an IWin32Window).
  3. Use SetWindowLong() with the GWLP_HWNDPARENT parameter.
  4. Use ShowDialog() as Mikael Svenson suggested.

This does require you to know the Excel applications window handle.

like image 131
shf301 Avatar answered Sep 21 '22 21:09

shf301


[Edit - changed code]

[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);

void func()
{
   Form1 f = new Form1();
   SetParent(f.Handle, (IntPtr)ThisAddIn.ExcelApplication.Hwnd);
   f.Show();
}
like image 42
Mikael Svenson Avatar answered Sep 23 '22 21:09

Mikael Svenson