Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you pass the owner window to Show() method overload?

I'm working on an Excel add in that opens a winform after the user clicks a button on a ribbon bar. This button needs to be non-modal so that the user can still interact with the parent window, but it also must remain on top of the parent window at all times. To accomplish this I'm trying to pass the parent window as a parameter into the Show() method. Here's my code:

Ribbon1.cs

    private void button2_Click(object sender, RibbonControlEventArgs e)
    {
        RangeSelectForm newForm = new RangeSelectForm();

        newForm.Show(this);
    }

The problem with this code is that the word 'this' references the ribbon class, not the parent window. I also tried passing in Globals.ThisAddIn.Application.Windows.Parent. This results in a runtime error "The best overloaded method match for 'System.Windows.Forms.Form.Show(System.Windows.Forms.IWin32Window)' has some invalid arguments". What is the correct way to pass the parent window to Show()?

In case it's relevant, this is an Office 2010 app written on .NET 4.0 using C#.

EDIT --- based on Slaks Answer

 using Excel = Microsoft.Office.Interop.Excel;

...

        class ArbitraryWindow : IWin32Window
        {
            public ArbitraryWindow(IntPtr handle) { Handle = handle; }
            public IntPtr Handle { get; private set; }
        }

        private void button2_Click(object sender, RibbonControlEventArgs e)
        {
            RangeSelectForm newForm = new RangeSelectForm();
            Excel.Application instance = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
            newForm.Show(new ArbitraryWindow(instance.Hwnd));
        }
like image 441
hughesdan Avatar asked Dec 25 '11 20:12

hughesdan


1 Answers

You need to create a class that implements IWin32Window and returns Excel's Application.Hwnd property.

For example:

class ArbitraryWindow : IWin32Window {
    public ArbitraryWindow(IntPtr handle) { Handle = handle; }
    public IntPtr Handle { get; private set; }
}

newForm.Show(new ArbitraryWindow(new IntPtr(Something.Application.Hwnd)));
like image 96
SLaks Avatar answered Nov 14 '22 23:11

SLaks