Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
449 views
in Technique[技术] by (71.8m points)

c# - 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));
        }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...