Loading a WPF Window without showing it

前端 未结 12 821
独厮守ぢ
独厮守ぢ 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:39

    I've noticed that the last thing that happens when the window is being initialized, is the change of WindowState, if it differs from normal. So, you can actually make use of it:

    public void InitializeWindow(Window window) {
        window.Top = Int32.MinValue;
        window.Left = Int32.MinValue;
    
        window.Width = 0;
        window.Height = 0;
    
        window.ShowActivated = false;
        window.ShowInTaskbar = false;
        window.Opacity = 0;
    
        window.StateChanged += OnBackgroundStateChanged;
    
        window.WindowStyle = WindowStyle.None;
    }
    
    public void ShowWindow(Window window) {
        window.Show();
        window.WindowState = WindowState.Maximized;
    }
    
    protected bool isStateChangeFirst = true;
    protected void OnBackgroundStateChanged(object sender, EventArgs e) {
        if (isStateChangeFirst) {
            isStateChangeFirst = false;
    
            window.Top = 300;
            window.Left = 200;
    
            window.Width = 760;
            window.Height = 400;
    
            window.WindowState = WindowState.Normal;
    
            window.ShowInTaskbar = true;
            window.Opacity = 1;
            window.Activate();
        }
    }
    

    That works fair enough for me. And it does not require working with any handles and stuff, and, more importantly, does not require to have a custom class for a window. Which is great for dynamically loaded XAML. And it is also a great way if you are making a fullscreen app. You do not even need to change its state back to normal or set proper width and height. Just go with

    protected bool isStateChangeFirst = true;
    protected void OnBackgroundStateChanged(object sender, EventArgs e) {
        if (isStateChangeFirst) {
            isStateChangeFirst = false;
    
            window.ShowInTaskbar = true;
            window.Opacity = 1;
            window.Activate();
        }
    }
    

    And you're done.

    And even if I am wrong in my assumption that change of state is last thing done when window is being loaded, you can still change to any other event, it does not really matter.

提交回复
热议问题