Hiren Gujarati
Hiren Gujarati

Reputation: 1049

How to make form topmost to the application only?

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 ........

Upvotes: 8

Views: 8089

Answers (2)

Mikael Svenson
Mikael Svenson

Reputation: 39695

[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();
}

Upvotes: 1

shf301
shf301

Reputation: 31404

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.

Upvotes: 13

Related Questions