如何将所有者窗口传递给Show()方法重载? [英] How do you pass the owner window to Show() method overload?

查看:69
本文介绍了如何将所有者窗口传递给Show()方法重载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Excel加载项,该加载项在用户单击功能区栏上的按钮后会打开winform.该按钮必须是非模式的,以便用户仍可以与父窗口进行交互,但是它也必须始终保持在父窗口的顶部.为此,我尝试将父窗口作为参数传递给Show()方法.这是我的代码:

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

Ribbon1.cs

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

        newForm.Show(this);
    }

此代码的问题是单词"this"引用了功能区类,而不是父窗口.我还尝试传递Globals.ThisAddIn.Application.Windows.Parent.这将导致运行时错误"System.Windows.Forms.Form.Show(System.Windows.Forms.IWin32Window)的最佳重载方法匹配具有一些无效的参数".将父窗口传递给Show()的正确方法是什么?

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()?

如果有意义,这是一个使用C#在.NET 4.0上编写的Office 2010应用程序.

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

编辑---基于Slaks答案

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

推荐答案

您需要创建一个实现IWin32Window并返回Excel的Application.Hwnd属性的类.

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

例如:

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

newForm.Show(new ArbitraryWindow(new IntPtr(Something.Application.Hwnd)));

这篇关于如何将所有者窗口传递给Show()方法重载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆