2017-10-19 125 views
0

問題如何觸發模式對話框在Microsoft PowerPoint/Office應用程序中關閉?

我試圖檢測並關閉使用VSTO插件在PowerPoint中打開的WPF對話框。當我使用this question的解決方案時,似乎無法正常工作,因爲System.Windows.Application.Current總是會返回null事件,即使打開了一個對話框。

代碼

不使用默認的Winform爲對話框,我的對話框是一個WPF窗口,例如,

<Window 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
     x:Name="Test" 
     WindowStyle="None" 
     SizeToContent="WidthAndHeight"> 
... 
</Window> 

這是後臺代碼:

namespace AddInProject.Classes 
{ 
    public partial class DlgCustomWindow:Window, IDisposable 
    { 
     public CustomWindow() 
     { 
      InitializeComponent(); 
     } 

     public Dispose() 
     { 
      this.Close(); 
     } 
    } 
} 

我使用此方法打開上述

WPF窗口

但運行System.Windows.Application.Current總是返回null。

回答

0

我使用的Win32 API的FindWindow查找對話框的指針參考使用對話框的標題或標題被關閉。然後我使用win32的SendMessage通過使用先前找到的指針引用來觸發正確的對話框關閉。

把這些代碼放到你的任何類:

[DllImport("user32.dll",SetLastError = true)] 
    private static extern IntPtr FindWindow(string lpClassName,string lpWindowName); 
    [DllImport("user32.dll",CharSet = CharSet.Auto)] 
    private static extern IntPtr SendMessage(IntPtr hWnd,UInt32 Msg,IntPtr wParam,IntPtr lParam); 

    public static bool CloseWindowIfOpen(string name = "") 
    { 
     IntPtr hWnd = (IntPtr)0; 
     hWnd = FindWindow(null,name); 
     if ((int)hWnd!=0) 
     { 
      //Close Window 
      SendMessage(hWnd,WM_CLOSE,IntPtr.Zero,IntPtr.Zero); 
      return true; 
     } 
     return false; 
    } 

所以可以使用,如:

到目前爲止

YourClass.CloseWindowIfOpen("CaptionOfModalDialog"); 

注意,我只能這樣做成功通過輸入要關閉的對話框的標題。你也應該能夠使用對話框的類名,但是我沒有成功。例如,我的對話框類名稱DlgCustomWindow位於命名空間:AddInProject.ClassesFindWindow無法找到模態對話框,當我用​​或FindWindow("AddInProject.Classes.DlgCustomWindow",name)