1

Problem

I'm trying to detect and close an opened WPF dialog box in PowerPoint using a VSTO addin. When I use the solution from this question, it doesn't seem to work because System.Windows.Application.Current always return null eventhough there is a dialog box opened.

Code

Instead of using the default Winform as dialog box, my dialog box is a WPF Window, e.g.,

<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>

This is the code-behind:

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

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

I use this method to open the WPF window above

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

But running System.Windows.Application.Current always return null.

John Evans Solachuk
  • 1,953
  • 5
  • 31
  • 67

1 Answers1

0

I use win32 API's FindWindow to find the pointer reference of the dialog box to be closed using the dialog box's caption or title. Then I use win32's SendMessage to trigger the correct dialog box to close by using the pointer reference that was found previously.

Put these code into any of your class:

    [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;
    }

So it can be used like:

YourClass.CloseWindowIfOpen("CaptionOfModalDialog");

Note

So far, I can only do this successfully by inputting the caption of the dialog box to be closed. You should also be able to use the class name of the dialog box but I have not succeeded in this. For example, my dialog box class name, DlgCustomWindow, is situated in namespace : AddInProject.Classes. FindWindow was not able to find the modal dialog when I used FindWindow("DlgCustomWindow",name) or FindWindow("AddInProject.Classes.DlgCustomWindow",name)

John Evans Solachuk
  • 1,953
  • 5
  • 31
  • 67