问题描述
我需要,为我的WPF应用程序,当DWM被接通/关断或系统主题改变时检测。
有一个在WinForms的这种情况,但我看不到任何在WPF。
I need, for my WPF app, to detect when the DWM is turned on/off or when the system theme changes.
There is such an event in WinForms, but I can't see any in WPF.
推荐答案
啊,所以它是获取的WinForms窗口调用 StyleChanged
事件。我的答案的其余部分仍然有效,但。
Ah, so it's the StyleChanged
event that gets invoked in WinForms windows. The rest of my answer still stands though.
WPF是不是密切相关的Windows API要么因为它是一个高层次的技术,投入大量的抽象远离内部。其一,它吸引的所有的通过本身就是一个窗口,并且不要求系统进行绘制,它(的编辑:这是为什么WPF缺少这样的 StyleChanged
事件)。也就是说,Windows发送消息给所有窗口时,DWM被触发,当主题的变化,你仍然可以深入到从WPF层来访问这些消息并操纵你的WPF相应的控制水平低。
WPF isn't closely tied to the Windows API either as it's a high-level technology that invests a lot of abstraction away from the internals. For one, it draws everything in a window by itself, and doesn't ask the system to do the drawing for it ( which is why WPF lacks such a StyleChanged
event). That said, Windows sends messages to all windows when the DWM is toggled and when the theme changes, and you can still drill down into the low level from the WPF layer to access these messages and manipulate your WPF controls accordingly.
附加窗口程序到您的WPF窗口的HWND(窗口句柄)作为窗口的 SourceInitialized
活动的一部分。在你的窗口过程,处理<$c$c>WM_DWMCOMPOSITIONCHANGED$c$c>和<$c$c>WM_THEMECHANGED$c$c>分别窗口消息。
Attach a window procedure to your WPF window's HWND (window handle) as part of your window's SourceInitialized
event. In your window procedure, handle the WM_DWMCOMPOSITIONCHANGED
and WM_THEMECHANGED
window messages respectively.
下面是一个简单的例子(与样板code改编自this矿山的问题):
Here's a quick example (with boilerplate code adapted from this question of mine):
private IntPtr hwnd;
private HwndSource hsource;
private void Window_SourceInitialized(object sender, EventArgs e)
{
if ((hwnd = new WindowInteropHelper(this).Handle) == IntPtr.Zero)
{
throw new InvalidOperationException("Could not get window handle.");
}
hsource = HwndSource.FromHwnd(hwnd);
hsource.AddHook(WndProc);
}
private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
switch (msg)
{
case WM_DWMCOMPOSITIONCHANGED: // Define this as 0x31A
case WM_THEMECHANGED: // Define this as 0x31E
// Respond to DWM being enabled/disabled or system theme being changed
return IntPtr.Zero;
default:
return IntPtr.Zero;
}
}
这篇关于检测在WPF系统主题变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!