Csharp/C#教程:如何将所有者窗口传递给Show()方法重载?分享


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

我正在处理Excel添加,在用户单击function区栏上的按钮后打开一个winform。 此按钮需要是非模态的,以便用户仍然可以与父窗口进行交互,但它也必须始终保持在父窗口的顶部。 为了实现这一点,我试图将父窗口作为参数传递给Show()方法。 这是我的代码:

Ribbon1.cs

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

此代码的问题是“this”一词引用了function区类,而不是父窗口。 我也试过传入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属性。

例如:

上述就是C#学习教程:如何将所有者窗口传递给Show()方法重载?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

 class ArbitraryWindow : IWin32Window { public ArbitraryWindow(IntPtr handle) { Handle = handle; } public IntPtr Handle { get; private set; } } newForm.Show(new ArbitraryWindow(new IntPtr(Something.Application.Hwnd))); 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1016008.html

(0)
上一篇 2021年12月31日
下一篇 2021年12月31日

精彩推荐