【问题标题】:How to trigger a modal dialog box to close in Microsoft PowerPoint / Office applications?如何在 Microsoft PowerPoint / Office 应用程序中触发模式对话框关闭?
【发布时间】:2017-10-19 10:37:51
【问题描述】:

问题

我正在尝试使用 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窗口

        using (DlgCustomWindow dlgCustom = new DlgCustomWindow())
        {
            dlgCustom.ShowDialog();
        }

但运行 System.Windows.Application.Current 总是返回 null。

【问题讨论】:

    标签: c# .net wpf vsto powerpoint


    【解决方案1】:

    我使用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("DlgCustomWindow",name)FindWindow("AddInProject.Classes.DlgCustomWindow",name) 时,FindWindow 找不到模态对话框

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-11
      • 1970-01-01
      • 1970-01-01
      • 2020-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多