如何触发模式对话框在Microsoft PowerPoint/Office应用程序中关闭?
问题描述:
问题如何触发模式对话框在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。
答
我使用的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.Classes
。 FindWindow
无法找到模态对话框,当我用或FindWindow("AddInProject.Classes.DlgCustomWindow",name)