2011-12-25 65 views
6

我正在使用Excel添加功能,在用戶單擊功能區欄上的按鈕後打開一個winform。此按鈕必須是非模態的,以便用戶仍可以與父窗口交互,但它也必須始終保持在父窗口之上。爲了做到這一點,我試圖將父窗口作爲參數傳遞給Show()方法。這裏是我的代碼:如何將所有者窗口傳遞給Show()方法重載?

Ribbon1.cs

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

     newForm.Show(this); 
    } 

這段代碼的問題是,這個詞「這」的引用帶類,而不是父窗口。我也嘗試傳遞Globals.ThisAddIn.Application.Windows.Parent。這會導致運行時錯誤「System.Windows.Forms.Form.Show(System.Windows.Forms.IWin32Window)'的最佳重載方法匹配'有一些無效參數」。將父窗口傳遞給Show()的正確方法是什麼?

如果相關,這是一個使用C#編寫的.NET 4.0應用程序。

編輯---基於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)); 
     } 
+0

其實更準確地說,我試圖從色帶火的窗口是一個Telerik的Radform。 – hughesdan 2011-12-25 20:53:22

+0

這是一個_compile-time_錯誤。 – SLaks 2011-12-25 20:53:50

+0

您應該能夠比插件屬性更容易地獲取應用程序。 – SLaks 2011-12-25 21:34:08

回答

14

你需要創建一個實現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))); 
+0

我得到「ExcelAddIn2.Globals的未知成員應用程序」 – hughesdan 2011-12-25 21:02:24

+0

我不知道在哪裏可以找到Excel'Application'實例,但是你應該有一個來自插件。 – SLaks 2011-12-25 21:03:12

+0

我在Microsoft.Office.Interop.Excel中找到它。但在修復後,我現在得到「未知構造函數Ribbon1.ArbitraryWindow(int)的ExcelAddIn2.Ribbon1.ArbitraryWindow。請參閱編輯我的問題的詳細信息。 – hughesdan 2011-12-25 21:30:02

相關問題