Search code examples
c#wpfinteropservices

How to Show a wpf window from another process


I have created 3 different application

Application 1: It is a WPF application it has 1 Window(MainWindow) which display "Hello Word".

Application 2: It is a WPF Application This application will create an instance of MainWindow of Application 1. like below

MainWindow window = new MainWindow();
//And it will store it's window handle to some file
string filePath = @"c:\windowHandle.txt";
var windowInteropHelper = new WindowInteropHelper(window);
File.WriteAllText(filePath, windowInteropHelper.EnsureHandle().ToString());

Application 3: This is again an WPF application which has 2 buttons "Show Application 1" and "Hide Application 1"

private void show_Click(object sender, RoutedEventArgs e)
{
    ShowWindow(GetWindowHandle(), 5);            
}        

private void hide_Click(object sender, RoutedEventArgs e)
{
    ShowWindow(GetWindowHandle(), 0);
}

private int GetWindowHandle()
{
    string handle = File.ReadAllText(@"C:\windowHandle.txt");
    return Convert.ToInt32(handle);
}

[DllImport("user32.dll")]
private static extern int ShowWindow(int hwnd, int nCmdShow);

Now I will launch Application 2 and Application 3. Once I click on "Show Application 1" button from Application 3, The window(Application 1) is coming with the black background. it is not showing "Hello world". It shows the window title but rest of the window is black.

If anyone has any idea how to fix it? Please let me know.

Please let me know if you have any query regarding my query :).


Solution

  • confirmed working

    App2:

    MainWindow window = new MainWindow();
    window.Show();
    //And it will store it's window handle to some file
    string filePath = @"c:\windowHandle.txt";
    var windowInteropHelper = new WindowInteropHelper(window);
    File.WriteAllText(filePath, windowInteropHelper.EnsureHandle().ToString());
    ShowWindow(windowInteropHelper.Handle.ToInt32(), 0);
    

    App3 as-is

    EDIT:

    from .net ReferenceSource:

    // RootVisual is not set until Show.
    // Only set RootVisual when we are going to show the window.
    if (!HwndCreatedButNotShown)
    {
        SetRootVisualAndUpdateSTC();
    }
    

    the comment says it all.. ;) if you just use winapi, no RootVisual is set...