Loading a WPF Window without showing it

前端 未结 12 817
独厮守ぢ
独厮守ぢ 2020-12-12 16:14

I create a global hot key to show a window by PInvoking RegisterHotKey(). But to do this I need that window\'s HWND, which doesn\'t exist until the

12条回答
  •  青春惊慌失措
    2020-12-12 16:57

    If you are targeting .NET 4.0 you can make use of the new EnsureHandle method available on the WindowInteropHelper:

    public void InitHwnd()
    {
        var helper = new WindowInteropHelper(this);
        helper.EnsureHandle();
    }
    

    (thanks to Thomas Levesque for pointing this out.)

    If you are targeting an older version of the .NET Framework, the easiest way is to show the window to get to the HWND while setting a few properties to make sure that the window is invisible and doesn't steal focus:

    var window = new Window() //make sure the window is invisible
    {
        Width = 0,
        Height = 0,
        WindowStyle = WindowStyle.None,
        ShowInTaskbar = false,
        ShowActivated = false
    };
    window.Show();
    

    Once you want to show the actual window you can then set the Content, the size and change the style back to a normal window.

提交回复
热议问题