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));
}
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)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With