c# - 如何将所有者窗口传递给 Show() 方法重载?

标签 c# winforms office-interop

我正在开发一个 Excel 插件,它会在用户单击功能区栏上的按钮后打开一个 winform。此按钮需要是非模态的,以便用户仍然可以与父窗口交互,但它也必须始终位于父窗口的顶部。为此,我尝试将父窗口作为参数传递给 Show() 方法。这是我的代码:

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() 的正确方法是什么?

如果相关的话,这是一个使用 C# 在 .NET 4.0 上编写的 Office 2010 应用。

编辑 --- 基于 Slaks 的回答

 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 属性的类。

例如:

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

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

关于c# - 如何将所有者窗口传递给 Show() 方法重载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8631491/

相关文章:

c# - 禁用 ToolStripMenuItem 突出显示?

c# - 如何过滤 ObjectListView 中的多个子项

com - 查找 MS Office Interop 常量的值,而不是对其进行硬编码

.net - 使用 Office 互操作获取特定窗口句柄

docker - Microsoft Word 在 Docker 容器中调用其 COM 时崩溃

c# - HtmlSanitizer + 带有 DI 的 ASP.NET Core 2

c# - 在没有堆栈溢出的情况下继续检查值

c# - 计算分页列表中要包含多少项目

C# 多重赋值

c# - 为什么单击动态创建的复选框列时会添加新行