加载 WPF 窗口而不显示它 [英] Loading a WPF Window without showing it

查看:25
本文介绍了加载 WPF 窗口而不显示它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过 PInvoking RegisterHotKey() 创建了一个全局热键来显示一个窗口.但是要做到这一点,我需要那个窗口的 HWND,它在窗口加载之前不存在,这意味着第一次显示.但是我不想在设置热键之前显示窗口.有没有办法为用户不可见的窗口创建 HWND ?

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 window is loaded, that means shown for the first time. But I don't want to show the window before I can set the hot key. Is there a way to create a HWND for that window that is invisible to the user?

推荐答案

如果您的目标是 .NET 4.0,您可以使用 WindowInteropHelperEnsureHandle 方法>:

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();
}

(感谢 Thomas Levesque 指出这一点.)

(thanks to Thomas Levesque for pointing this out.)

如果您的目标是旧版本的 .NET Framework,最简单的方法是显示窗口以访问 HWND,同时设置一些属性以确保窗口不可见且不会窃取焦点:

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.

这篇关于加载 WPF 窗口而不显示它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆