2017-10-19 90 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)

相关问题