From 0d51199b6dfe90f0320b91da61651d9f0e35d61a Mon Sep 17 00:00:00 2001 From: Peter Date: Sat, 29 Jun 2024 20:44:19 +0800 Subject: [PATCH 1/5] Feat: Implement ThemeListener for winui3 --- components/Helpers/src/ThemeListener.cs | 11 + .../Helpers/src/ThemeListenerHelperWindow.cs | 326 ++++++++++++++++++ 2 files changed, 337 insertions(+) create mode 100644 components/Helpers/src/ThemeListenerHelperWindow.cs diff --git a/components/Helpers/src/ThemeListener.cs b/components/Helpers/src/ThemeListener.cs index ecd04b13..aaacbf56 100644 --- a/components/Helpers/src/ThemeListener.cs +++ b/components/Helpers/src/ThemeListener.cs @@ -4,6 +4,8 @@ using Windows.Foundation.Metadata; using Windows.UI.ViewManagement; +using CommunityToolkit.WinUI.HelpersRns; + #if !WINAPPSDK using Windows.System; @@ -83,6 +85,15 @@ public ThemeListener(DispatcherQueue? dispatcherQueue = null) Window.Current.CoreWindow.Activated += CoreWindow_Activated; } +#if WINAPPSDK + ThemeListenerHelperWindow.Instance.ThemeChanged += this.Instance_ThemeChanged; +#endif + } + + private void Instance_ThemeChanged(ApplicationTheme theme) + { + CurrentTheme = theme; + ThemeChanged?.Invoke(this); } private async void Accessible_HighContrastChanged(AccessibilitySettings sender, object args) diff --git a/components/Helpers/src/ThemeListenerHelperWindow.cs b/components/Helpers/src/ThemeListenerHelperWindow.cs new file mode 100644 index 00000000..6d44cc38 --- /dev/null +++ b/components/Helpers/src/ThemeListenerHelperWindow.cs @@ -0,0 +1,326 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using Microsoft.Win32; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading.Tasks; + +namespace CommunityToolkit.WinUI.HelpersRns; + +#if WINAPPSDK +internal static class WinAPI +{ + [Flags] + public enum WindowStyles : uint + { + /// The window has a thin-line border. + WS_BORDER = 0x800000, + + /// The window has a title bar (includes the WS_BORDER style). + WS_CAPTION = 0xc00000, + + /// The window is a child window. A window with this style cannot have a menu bar. This style cannot be used with the WS_POPUP style. + WS_CHILD = 0x40000000, + + /// Excludes the area occupied by child windows when drawing occurs within the parent window. This style is used when creating the parent window. + WS_CLIPCHILDREN = 0x2000000, + + /// + /// Clips child windows relative to each other; that is, when a particular child window receives a WM_PAINT message, the WS_CLIPSIBLINGS style clips all other overlapping child windows out of the region of the child window to be updated. + /// If WS_CLIPSIBLINGS is not specified and child windows overlap, it is possible, when drawing within the client area of a child window, to draw within the client area of a neighboring child window. + /// + WS_CLIPSIBLINGS = 0x4000000, + + /// The window is initially disabled. A disabled window cannot receive input from the user. To change this after a window has been created, use the EnableWindow function. + WS_DISABLED = 0x8000000, + + /// The window has a border of a style typically used with dialog boxes. A window with this style cannot have a title bar. + WS_DLGFRAME = 0x400000, + + /// + /// The window is the first control of a group of controls. The group consists of this first control and all controls defined after it, up to the next control with the WS_GROUP style. + /// The first control in each group usually has the WS_TABSTOP style so that the user can move from group to group. The user can subsequently change the keyboard focus from one control in the group to the next control in the group by using the direction keys. + /// You can turn this style on and off to change dialog box navigation. To change this style after a window has been created, use the SetWindowLong function. + /// + WS_GROUP = 0x20000, + + /// The window has a horizontal scroll bar. + WS_HSCROLL = 0x100000, + + /// The window is initially maximized. + WS_MAXIMIZE = 0x1000000, + + /// The window has a maximize button. Cannot be combined with the WS_EX_CONTEXTHELP style. The WS_SYSMENU style must also be specified. + WS_MAXIMIZEBOX = 0x10000, + + /// The window is initially minimized. + WS_MINIMIZE = 0x20000000, + + /// The window has a minimize button. Cannot be combined with the WS_EX_CONTEXTHELP style. The WS_SYSMENU style must also be specified. + WS_MINIMIZEBOX = 0x20000, + + /// The window is an overlapped window. An overlapped window has a title bar and a border. + WS_OVERLAPPED = 0x0, + + /// The window is an overlapped window. + WS_OVERLAPPEDWINDOW = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_SIZEFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX, + + /// The window is a pop-up window. This style cannot be used with the WS_CHILD style. + WS_POPUP = 0x80000000u, + + /// The window is a pop-up window. The WS_CAPTION and WS_POPUPWINDOW styles must be combined to make the window menu visible. + WS_POPUPWINDOW = WS_POPUP | WS_BORDER | WS_SYSMENU, + + /// The window has a sizing border. + WS_SIZEFRAME = 0x40000, + + /// The window has a window menu on its title bar. The WS_CAPTION style must also be specified. + WS_SYSMENU = 0x80000, + + /// + /// The window is a control that can receive the keyboard focus when the user presses the TAB key. + /// Pressing the TAB key changes the keyboard focus to the next control with the WS_TABSTOP style. + /// You can turn this style on and off to change dialog box navigation. To change this style after a window has been created, use the SetWindowLong function. + /// For user-created windows and modeless dialogs to work with tab stops, alter the message loop to call the IsDialogMessage function. + /// + WS_TABSTOP = 0x10000, + + /// The window is initially visible. This style can be turned on and off by using the ShowWindow or SetWindowPos function. + WS_VISIBLE = 0x10000000, + + /// The window has a vertical scroll bar. + WS_VSCROLL = 0x200000 + } + + [Flags] + public enum WindowStylesEx : uint + { + /// + /// Specifies that a window created with this style accepts drag-drop files. + /// + WS_EX_ACCEPTFILES = 0x00000010, + /// + /// Forces a top-level window onto the taskbar when the window is visible. + /// + WS_EX_APPWINDOW = 0x00040000, + /// + /// Specifies that a window has a border with a sunken edge. + /// + WS_EX_CLIENTEDGE = 0x00000200, + /// + /// Windows XP: Paints all descendants of a window in bottom-to-top painting order using double-buffering. For more information, see Remarks. This cannot be used if the window has a class style of either CS_OWNDC or CS_CLASSDC. + /// + WS_EX_COMPOSITED = 0x02000000, + /// + /// Includes a question mark in the title bar of the window. When the user clicks the question mark, the cursor changes to a question mark with a pointer. If the user then clicks a child window, the child receives a WM_HELP message. The child window should pass the message to the parent window procedure, which should call the WinHelp function using the HELP_WM_HELP command. The Help application displays a pop-up window that typically contains help for the child window. + /// WS_EX_CONTEXTHELP cannot be used with the WS_MAXIMIZEBOX or WS_MINIMIZEBOX styles. + /// + WS_EX_CONTEXTHELP = 0x00000400, + /// + /// The window itself contains child windows that should take part in dialog box navigation. If this style is specified, the dialog manager recurses into children of this window when performing navigation operations such as handling the TAB key, an arrow key, or a keyboard mnemonic. + /// + WS_EX_CONTROLPARENT = 0x00010000, + /// + /// Creates a window that has a double border; the window can, optionally, be created with a title bar by specifying the WS_CAPTION style in the dwStyle parameter. + /// + WS_EX_DLGMODALFRAME = 0x00000001, + /// + /// Windows 2000/XP: Creates a layered window. Note that this cannot be used for child windows. Also, this cannot be used if the window has a class style of either CS_OWNDC or CS_CLASSDC. + /// + WS_EX_LAYERED = 0x00080000, + /// + /// Arabic and Hebrew versions of Windows 98/Me, Windows 2000/XP: Creates a window whose horizontal origin is on the right edge. Increasing horizontal values advance to the left. + /// + WS_EX_LAYOUTRTL = 0x00400000, + /// + /// Creates a window that has generic left-aligned properties. This is the default. + /// + WS_EX_LEFT = 0x00000000, + /// + /// If the shell language is Hebrew, Arabic, or another language that supports reading order alignment, the vertical scroll bar (if present) is to the left of the client area. For other languages, the style is ignored. + /// + WS_EX_LEFTSCROLLBAR = 0x00004000, + /// + /// The window text is displayed using left-to-right reading-order properties. This is the default. + /// + WS_EX_LTRREADING = 0x00000000, + /// + /// Creates a multiple-document interface (MDI) child window. + /// + WS_EX_MDICHILD = 0x00000040, + /// + /// Windows 2000/XP: A top-level window created with this style does not become the foreground window when the user clicks it. The system does not bring this window to the foreground when the user minimizes or closes the foreground window. + /// To activate the window, use the SetActiveWindow or SetForegroundWindow function. + /// The window does not appear on the taskbar by default. To force the window to appear on the taskbar, use the WS_EX_APPWINDOW style. + /// + WS_EX_NOACTIVATE = 0x08000000, + /// + /// Windows 2000/XP: A window created with this style does not pass its window layout to its child windows. + /// + WS_EX_NOINHERITLAYOUT = 0x00100000, + /// + /// Specifies that a child window created with this style does not send the WM_PARENTNOTIFY message to its parent window when it is created or destroyed. + /// + WS_EX_NOPARENTNOTIFY = 0x00000004, + /// + /// Combines the WS_EX_CLIENTEDGE and WS_EX_WINDOWEDGE styles. + /// + WS_EX_OVERLAPPEDWINDOW = WS_EX_WINDOWEDGE | WS_EX_CLIENTEDGE, + /// + /// Combines the WS_EX_WINDOWEDGE, WS_EX_TOOLWINDOW, and WS_EX_TOPMOST styles. + /// + WS_EX_PALETTEWINDOW = WS_EX_WINDOWEDGE | WS_EX_TOOLWINDOW | WS_EX_TOPMOST, + /// + /// The window has generic "right-aligned" properties. This depends on the window class. This style has an effect only if the shell language is Hebrew, Arabic, or another language that supports reading-order alignment; otherwise, the style is ignored. + /// Using the WS_EX_RIGHT style for static or edit controls has the same effect as using the SS_RIGHT or ES_RIGHT style, respectively. Using this style with button controls has the same effect as using BS_RIGHT and BS_RIGHTBUTTON styles. + /// + WS_EX_RIGHT = 0x00001000, + /// + /// Vertical scroll bar (if present) is to the right of the client area. This is the default. + /// + WS_EX_RIGHTSCROLLBAR = 0x00000000, + /// + /// If the shell language is Hebrew, Arabic, or another language that supports reading-order alignment, the window text is displayed using right-to-left reading-order properties. For other languages, the style is ignored. + /// + WS_EX_RTLREADING = 0x00002000, + /// + /// Creates a window with a three-dimensional border style intended to be used for items that do not accept user input. + /// + WS_EX_STATICEDGE = 0x00020000, + /// + /// Creates a tool window; that is, a window intended to be used as a floating toolbar. A tool window has a title bar that is shorter than a normal title bar, and the window title is drawn using a smaller font. A tool window does not appear in the taskbar or in the dialog that appears when the user presses ALT+TAB. If a tool window has a system menu, its icon is not displayed on the title bar. However, you can display the system menu by right-clicking or by typing ALT+SPACE. + /// + WS_EX_TOOLWINDOW = 0x00000080, + /// + /// Specifies that a window created with this style should be placed above all non-topmost windows and should stay above them, even when the window is deactivated. To add or remove this style, use the SetWindowPos function. + /// + WS_EX_TOPMOST = 0x00000008, + /// + /// Specifies that a window created with this style should not be painted until siblings beneath the window (that were created by the same thread) have been painted. The window appears transparent because the bits of underlying sibling windows have already been painted. + /// To achieve transparency without these restrictions, use the SetWindowRgn function. + /// + WS_EX_TRANSPARENT = 0x00000020, + /// + /// Specifies that a window has a border with a raised edge. + /// + WS_EX_WINDOWEDGE = 0x00000100 + } + + [DllImport("user32.dll", SetLastError = true, EntryPoint = "CreateWindowEx")] + public static extern IntPtr CreateWindowEx( + WindowStylesEx dwExStyle, + string lpClassName, + string lpWindowName, + WindowStyles dwStyle, + int x, + int y, + int nWidth, + int nHeight, + IntPtr hWndParent, + IntPtr hMenu, + IntPtr hInstance, + IntPtr lpParam); + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] + public struct WNDCLASSEX + { + [MarshalAs(UnmanagedType.U4)] + public int cbSize; + [MarshalAs(UnmanagedType.U4)] + public int style; + public IntPtr lpfnWndProc; // not WndProc -- careful + public int cbClsExtra; + public int cbWndExtra; + public IntPtr hInstance; + public IntPtr hIcon; + public IntPtr hCursor; + public IntPtr hbrBackground; + [MarshalAs(UnmanagedType.LPStr)] + public string lpszMenuName; + [MarshalAs(UnmanagedType.LPStr)] + public string lpszClassName; + public IntPtr hIconSm; + } + + [DllImport("user32.dll")] + public static extern short RegisterClassEx([In] ref WNDCLASSEX lpwcx); + + + public enum WM : uint + { + SettingChange = 0x001A + } + + [DllImport("user32.dll")] + public static extern IntPtr DefWindowProc(IntPtr hWnd, WM uMsg, IntPtr wParam, IntPtr lParam); +} + +internal class ThemeListenerHelperWindow +{ + public delegate void ThemeChangedHandler(ApplicationTheme theme); + + public static ThemeListenerHelperWindow Instance = new(); + private static string s_className = "ThemeListenerHelperWindow"; + private IntPtr m_hwnd; + public event ThemeChangedHandler? ThemeChanged; + delegate IntPtr WndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam); + private WndProc m_wnd_proc_delegate; + private void registerClass() + { + var wcx = new WinAPI.WNDCLASSEX(); + wcx.cbSize = Marshal.SizeOf(wcx); + wcx.lpszClassName = s_className; + wcx.lpfnWndProc = Marshal.GetFunctionPointerForDelegate(m_wnd_proc_delegate); + if(WinAPI.RegisterClassEx(ref wcx) == 0) + { + Debug.WriteLine(new Win32Exception(Marshal.GetLastWin32Error()).Message); + } + } + + static IntPtr wndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam) + { + switch (msg) + { + case (uint)WinAPI.WM.SettingChange: + var value = Registry.GetValue("""HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize""", "AppsUseLightTheme", true); + if (value != null) + { + Instance.ThemeChanged?.Invoke((int)value == 1 ? ApplicationTheme.Light : ApplicationTheme.Dark); + } + break; + } + return WinAPI.DefWindowProc(hWnd, (WinAPI.WM)msg, wParam, lParam); + } + + private static IntPtr createWindow() + { + var hwnd = WinAPI.CreateWindowEx( + 0, + s_className, + "", + 0, + 0, 0, 0, 0, + IntPtr.Zero, + IntPtr.Zero, + IntPtr.Zero, + IntPtr.Zero); + if (hwnd == IntPtr.Zero) + { + Debug.WriteLine(new Win32Exception(Marshal.GetLastWin32Error()).Message); + } + return hwnd; + } + private ThemeListenerHelperWindow() + { + m_wnd_proc_delegate = wndProc; + s_className = "ThemeListenerHelperWindow"; + registerClass(); + m_hwnd = createWindow(); + } +} +#endif From 290fdcb8ebed8c5c26d1adcd175d01939d3150eb Mon Sep 17 00:00:00 2001 From: Peter Date: Wed, 10 Jul 2024 23:18:35 +0800 Subject: [PATCH 2/5] Use CsWin32 --- .../src/CommunityToolkit.WinUI.Helpers.csproj | 9 +- components/Helpers/src/NativeMethods.txt | 4 + .../Helpers/src/ThemeListenerHelperWindow.cs | 292 ++---------------- 3 files changed, 41 insertions(+), 264 deletions(-) create mode 100644 components/Helpers/src/NativeMethods.txt diff --git a/components/Helpers/src/CommunityToolkit.WinUI.Helpers.csproj b/components/Helpers/src/CommunityToolkit.WinUI.Helpers.csproj index c586beef..76f50f8f 100644 --- a/components/Helpers/src/CommunityToolkit.WinUI.Helpers.csproj +++ b/components/Helpers/src/CommunityToolkit.WinUI.Helpers.csproj @@ -11,7 +11,7 @@ - + @@ -20,6 +20,13 @@ \ + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + diff --git a/components/Helpers/src/NativeMethods.txt b/components/Helpers/src/NativeMethods.txt new file mode 100644 index 00000000..3da417f6 --- /dev/null +++ b/components/Helpers/src/NativeMethods.txt @@ -0,0 +1,4 @@ +RegisterClassEx +DefWindowProc +CreateWindowEx +WM_SETTINGCHANGE diff --git a/components/Helpers/src/ThemeListenerHelperWindow.cs b/components/Helpers/src/ThemeListenerHelperWindow.cs index 6d44cc38..93a70cf0 100644 --- a/components/Helpers/src/ThemeListenerHelperWindow.cs +++ b/components/Helpers/src/ThemeListenerHelperWindow.cs @@ -9,256 +9,11 @@ using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; +using Windows.Win32; namespace CommunityToolkit.WinUI.HelpersRns; #if WINAPPSDK -internal static class WinAPI -{ - [Flags] - public enum WindowStyles : uint - { - /// The window has a thin-line border. - WS_BORDER = 0x800000, - - /// The window has a title bar (includes the WS_BORDER style). - WS_CAPTION = 0xc00000, - - /// The window is a child window. A window with this style cannot have a menu bar. This style cannot be used with the WS_POPUP style. - WS_CHILD = 0x40000000, - - /// Excludes the area occupied by child windows when drawing occurs within the parent window. This style is used when creating the parent window. - WS_CLIPCHILDREN = 0x2000000, - - /// - /// Clips child windows relative to each other; that is, when a particular child window receives a WM_PAINT message, the WS_CLIPSIBLINGS style clips all other overlapping child windows out of the region of the child window to be updated. - /// If WS_CLIPSIBLINGS is not specified and child windows overlap, it is possible, when drawing within the client area of a child window, to draw within the client area of a neighboring child window. - /// - WS_CLIPSIBLINGS = 0x4000000, - - /// The window is initially disabled. A disabled window cannot receive input from the user. To change this after a window has been created, use the EnableWindow function. - WS_DISABLED = 0x8000000, - - /// The window has a border of a style typically used with dialog boxes. A window with this style cannot have a title bar. - WS_DLGFRAME = 0x400000, - - /// - /// The window is the first control of a group of controls. The group consists of this first control and all controls defined after it, up to the next control with the WS_GROUP style. - /// The first control in each group usually has the WS_TABSTOP style so that the user can move from group to group. The user can subsequently change the keyboard focus from one control in the group to the next control in the group by using the direction keys. - /// You can turn this style on and off to change dialog box navigation. To change this style after a window has been created, use the SetWindowLong function. - /// - WS_GROUP = 0x20000, - - /// The window has a horizontal scroll bar. - WS_HSCROLL = 0x100000, - - /// The window is initially maximized. - WS_MAXIMIZE = 0x1000000, - - /// The window has a maximize button. Cannot be combined with the WS_EX_CONTEXTHELP style. The WS_SYSMENU style must also be specified. - WS_MAXIMIZEBOX = 0x10000, - - /// The window is initially minimized. - WS_MINIMIZE = 0x20000000, - - /// The window has a minimize button. Cannot be combined with the WS_EX_CONTEXTHELP style. The WS_SYSMENU style must also be specified. - WS_MINIMIZEBOX = 0x20000, - - /// The window is an overlapped window. An overlapped window has a title bar and a border. - WS_OVERLAPPED = 0x0, - - /// The window is an overlapped window. - WS_OVERLAPPEDWINDOW = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_SIZEFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX, - - /// The window is a pop-up window. This style cannot be used with the WS_CHILD style. - WS_POPUP = 0x80000000u, - - /// The window is a pop-up window. The WS_CAPTION and WS_POPUPWINDOW styles must be combined to make the window menu visible. - WS_POPUPWINDOW = WS_POPUP | WS_BORDER | WS_SYSMENU, - - /// The window has a sizing border. - WS_SIZEFRAME = 0x40000, - - /// The window has a window menu on its title bar. The WS_CAPTION style must also be specified. - WS_SYSMENU = 0x80000, - - /// - /// The window is a control that can receive the keyboard focus when the user presses the TAB key. - /// Pressing the TAB key changes the keyboard focus to the next control with the WS_TABSTOP style. - /// You can turn this style on and off to change dialog box navigation. To change this style after a window has been created, use the SetWindowLong function. - /// For user-created windows and modeless dialogs to work with tab stops, alter the message loop to call the IsDialogMessage function. - /// - WS_TABSTOP = 0x10000, - - /// The window is initially visible. This style can be turned on and off by using the ShowWindow or SetWindowPos function. - WS_VISIBLE = 0x10000000, - - /// The window has a vertical scroll bar. - WS_VSCROLL = 0x200000 - } - - [Flags] - public enum WindowStylesEx : uint - { - /// - /// Specifies that a window created with this style accepts drag-drop files. - /// - WS_EX_ACCEPTFILES = 0x00000010, - /// - /// Forces a top-level window onto the taskbar when the window is visible. - /// - WS_EX_APPWINDOW = 0x00040000, - /// - /// Specifies that a window has a border with a sunken edge. - /// - WS_EX_CLIENTEDGE = 0x00000200, - /// - /// Windows XP: Paints all descendants of a window in bottom-to-top painting order using double-buffering. For more information, see Remarks. This cannot be used if the window has a class style of either CS_OWNDC or CS_CLASSDC. - /// - WS_EX_COMPOSITED = 0x02000000, - /// - /// Includes a question mark in the title bar of the window. When the user clicks the question mark, the cursor changes to a question mark with a pointer. If the user then clicks a child window, the child receives a WM_HELP message. The child window should pass the message to the parent window procedure, which should call the WinHelp function using the HELP_WM_HELP command. The Help application displays a pop-up window that typically contains help for the child window. - /// WS_EX_CONTEXTHELP cannot be used with the WS_MAXIMIZEBOX or WS_MINIMIZEBOX styles. - /// - WS_EX_CONTEXTHELP = 0x00000400, - /// - /// The window itself contains child windows that should take part in dialog box navigation. If this style is specified, the dialog manager recurses into children of this window when performing navigation operations such as handling the TAB key, an arrow key, or a keyboard mnemonic. - /// - WS_EX_CONTROLPARENT = 0x00010000, - /// - /// Creates a window that has a double border; the window can, optionally, be created with a title bar by specifying the WS_CAPTION style in the dwStyle parameter. - /// - WS_EX_DLGMODALFRAME = 0x00000001, - /// - /// Windows 2000/XP: Creates a layered window. Note that this cannot be used for child windows. Also, this cannot be used if the window has a class style of either CS_OWNDC or CS_CLASSDC. - /// - WS_EX_LAYERED = 0x00080000, - /// - /// Arabic and Hebrew versions of Windows 98/Me, Windows 2000/XP: Creates a window whose horizontal origin is on the right edge. Increasing horizontal values advance to the left. - /// - WS_EX_LAYOUTRTL = 0x00400000, - /// - /// Creates a window that has generic left-aligned properties. This is the default. - /// - WS_EX_LEFT = 0x00000000, - /// - /// If the shell language is Hebrew, Arabic, or another language that supports reading order alignment, the vertical scroll bar (if present) is to the left of the client area. For other languages, the style is ignored. - /// - WS_EX_LEFTSCROLLBAR = 0x00004000, - /// - /// The window text is displayed using left-to-right reading-order properties. This is the default. - /// - WS_EX_LTRREADING = 0x00000000, - /// - /// Creates a multiple-document interface (MDI) child window. - /// - WS_EX_MDICHILD = 0x00000040, - /// - /// Windows 2000/XP: A top-level window created with this style does not become the foreground window when the user clicks it. The system does not bring this window to the foreground when the user minimizes or closes the foreground window. - /// To activate the window, use the SetActiveWindow or SetForegroundWindow function. - /// The window does not appear on the taskbar by default. To force the window to appear on the taskbar, use the WS_EX_APPWINDOW style. - /// - WS_EX_NOACTIVATE = 0x08000000, - /// - /// Windows 2000/XP: A window created with this style does not pass its window layout to its child windows. - /// - WS_EX_NOINHERITLAYOUT = 0x00100000, - /// - /// Specifies that a child window created with this style does not send the WM_PARENTNOTIFY message to its parent window when it is created or destroyed. - /// - WS_EX_NOPARENTNOTIFY = 0x00000004, - /// - /// Combines the WS_EX_CLIENTEDGE and WS_EX_WINDOWEDGE styles. - /// - WS_EX_OVERLAPPEDWINDOW = WS_EX_WINDOWEDGE | WS_EX_CLIENTEDGE, - /// - /// Combines the WS_EX_WINDOWEDGE, WS_EX_TOOLWINDOW, and WS_EX_TOPMOST styles. - /// - WS_EX_PALETTEWINDOW = WS_EX_WINDOWEDGE | WS_EX_TOOLWINDOW | WS_EX_TOPMOST, - /// - /// The window has generic "right-aligned" properties. This depends on the window class. This style has an effect only if the shell language is Hebrew, Arabic, or another language that supports reading-order alignment; otherwise, the style is ignored. - /// Using the WS_EX_RIGHT style for static or edit controls has the same effect as using the SS_RIGHT or ES_RIGHT style, respectively. Using this style with button controls has the same effect as using BS_RIGHT and BS_RIGHTBUTTON styles. - /// - WS_EX_RIGHT = 0x00001000, - /// - /// Vertical scroll bar (if present) is to the right of the client area. This is the default. - /// - WS_EX_RIGHTSCROLLBAR = 0x00000000, - /// - /// If the shell language is Hebrew, Arabic, or another language that supports reading-order alignment, the window text is displayed using right-to-left reading-order properties. For other languages, the style is ignored. - /// - WS_EX_RTLREADING = 0x00002000, - /// - /// Creates a window with a three-dimensional border style intended to be used for items that do not accept user input. - /// - WS_EX_STATICEDGE = 0x00020000, - /// - /// Creates a tool window; that is, a window intended to be used as a floating toolbar. A tool window has a title bar that is shorter than a normal title bar, and the window title is drawn using a smaller font. A tool window does not appear in the taskbar or in the dialog that appears when the user presses ALT+TAB. If a tool window has a system menu, its icon is not displayed on the title bar. However, you can display the system menu by right-clicking or by typing ALT+SPACE. - /// - WS_EX_TOOLWINDOW = 0x00000080, - /// - /// Specifies that a window created with this style should be placed above all non-topmost windows and should stay above them, even when the window is deactivated. To add or remove this style, use the SetWindowPos function. - /// - WS_EX_TOPMOST = 0x00000008, - /// - /// Specifies that a window created with this style should not be painted until siblings beneath the window (that were created by the same thread) have been painted. The window appears transparent because the bits of underlying sibling windows have already been painted. - /// To achieve transparency without these restrictions, use the SetWindowRgn function. - /// - WS_EX_TRANSPARENT = 0x00000020, - /// - /// Specifies that a window has a border with a raised edge. - /// - WS_EX_WINDOWEDGE = 0x00000100 - } - - [DllImport("user32.dll", SetLastError = true, EntryPoint = "CreateWindowEx")] - public static extern IntPtr CreateWindowEx( - WindowStylesEx dwExStyle, - string lpClassName, - string lpWindowName, - WindowStyles dwStyle, - int x, - int y, - int nWidth, - int nHeight, - IntPtr hWndParent, - IntPtr hMenu, - IntPtr hInstance, - IntPtr lpParam); - - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] - public struct WNDCLASSEX - { - [MarshalAs(UnmanagedType.U4)] - public int cbSize; - [MarshalAs(UnmanagedType.U4)] - public int style; - public IntPtr lpfnWndProc; // not WndProc -- careful - public int cbClsExtra; - public int cbWndExtra; - public IntPtr hInstance; - public IntPtr hIcon; - public IntPtr hCursor; - public IntPtr hbrBackground; - [MarshalAs(UnmanagedType.LPStr)] - public string lpszMenuName; - [MarshalAs(UnmanagedType.LPStr)] - public string lpszClassName; - public IntPtr hIconSm; - } - - [DllImport("user32.dll")] - public static extern short RegisterClassEx([In] ref WNDCLASSEX lpwcx); - - - public enum WM : uint - { - SettingChange = 0x001A - } - - [DllImport("user32.dll")] - public static extern IntPtr DefWindowProc(IntPtr hWnd, WM uMsg, IntPtr wParam, IntPtr lParam); -} internal class ThemeListenerHelperWindow { @@ -268,47 +23,58 @@ internal class ThemeListenerHelperWindow private static string s_className = "ThemeListenerHelperWindow"; private IntPtr m_hwnd; public event ThemeChangedHandler? ThemeChanged; - delegate IntPtr WndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam); + delegate Windows.Win32.Foundation.LRESULT WndProc(Windows.Win32.Foundation.HWND hWnd, uint msg, Windows.Win32.Foundation.WPARAM wParam, Windows.Win32.Foundation.LPARAM lParam); private WndProc m_wnd_proc_delegate; private void registerClass() { - var wcx = new WinAPI.WNDCLASSEX(); - wcx.cbSize = Marshal.SizeOf(wcx); - wcx.lpszClassName = s_className; - wcx.lpfnWndProc = Marshal.GetFunctionPointerForDelegate(m_wnd_proc_delegate); - if(WinAPI.RegisterClassEx(ref wcx) == 0) + unsafe { - Debug.WriteLine(new Win32Exception(Marshal.GetLastWin32Error()).Message); + var wcx = new Windows.Win32.UI.WindowsAndMessaging.WNDCLASSEXW(); + wcx.cbSize = (uint)Marshal.SizeOf(wcx); + fixed (char* pClassName = s_className) + { + wcx.lpszClassName = new Windows.Win32.Foundation.PCWSTR(pClassName); + } + wcx.lpfnWndProc = wndProc; + if (PInvoke.RegisterClassEx(in wcx) == 0) + { + Debug.WriteLine(new Win32Exception(Marshal.GetLastWin32Error()).Message); + } } + } - static IntPtr wndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam) + static Windows.Win32.Foundation.LRESULT wndProc(Windows.Win32.Foundation.HWND hWnd, uint msg, Windows.Win32.Foundation.WPARAM wParam, Windows.Win32.Foundation.LPARAM lParam) { switch (msg) { - case (uint)WinAPI.WM.SettingChange: - var value = Registry.GetValue("""HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize""", "AppsUseLightTheme", true); + case PInvoke.WM_SETTINGCHANGE: + var value = Registry.GetValue( + """HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize""", + "AppsUseLightTheme", + true + ); if (value != null) { Instance.ThemeChanged?.Invoke((int)value == 1 ? ApplicationTheme.Light : ApplicationTheme.Dark); } break; } - return WinAPI.DefWindowProc(hWnd, (WinAPI.WM)msg, wParam, lParam); + return PInvoke.DefWindowProc(hWnd, msg, wParam, lParam); } - private static IntPtr createWindow() + unsafe private static IntPtr createWindow() { - var hwnd = WinAPI.CreateWindowEx( + var hwnd = PInvoke.CreateWindowEx( 0, s_className, "", 0, 0, 0, 0, 0, - IntPtr.Zero, - IntPtr.Zero, - IntPtr.Zero, - IntPtr.Zero); + new Windows.Win32.Foundation.HWND(), + null, + null, + null); if (hwnd == IntPtr.Zero) { Debug.WriteLine(new Win32Exception(Marshal.GetLastWin32Error()).Message); From 9287da42cb613dd1ebe89558bba24d1d593ab572 Mon Sep 17 00:00:00 2001 From: DismissedLight <1686188646@qq.com> Date: Mon, 30 Sep 2024 10:28:40 +0800 Subject: [PATCH 3/5] code style --- .../src/CommunityToolkit.WinUI.Helpers.csproj | 3 + components/Helpers/src/MultiTarget.props | 2 +- components/Helpers/src/NativeMethods.json | 3 + .../Helpers/src/ThemeListenerHelperWindow.cs | 101 ++++++++---------- 4 files changed, 51 insertions(+), 58 deletions(-) create mode 100644 components/Helpers/src/NativeMethods.json diff --git a/components/Helpers/src/CommunityToolkit.WinUI.Helpers.csproj b/components/Helpers/src/CommunityToolkit.WinUI.Helpers.csproj index 76f50f8f..8157235a 100644 --- a/components/Helpers/src/CommunityToolkit.WinUI.Helpers.csproj +++ b/components/Helpers/src/CommunityToolkit.WinUI.Helpers.csproj @@ -30,4 +30,7 @@ + + + diff --git a/components/Helpers/src/MultiTarget.props b/components/Helpers/src/MultiTarget.props index b11c1942..c780abff 100644 --- a/components/Helpers/src/MultiTarget.props +++ b/components/Helpers/src/MultiTarget.props @@ -6,4 +6,4 @@ --> uwp;wasdk;wpf;wasm;linuxgtk;macos;ios;android; - \ No newline at end of file + diff --git a/components/Helpers/src/NativeMethods.json b/components/Helpers/src/NativeMethods.json new file mode 100644 index 00000000..9725d209 --- /dev/null +++ b/components/Helpers/src/NativeMethods.json @@ -0,0 +1,3 @@ +{ + "allowMarshaling": false +} diff --git a/components/Helpers/src/ThemeListenerHelperWindow.cs b/components/Helpers/src/ThemeListenerHelperWindow.cs index 93a70cf0..e4a7944c 100644 --- a/components/Helpers/src/ThemeListenerHelperWindow.cs +++ b/components/Helpers/src/ThemeListenerHelperWindow.cs @@ -3,90 +3,77 @@ // See the LICENSE file in the project root for more information. using Microsoft.Win32; -using System; -using System.Collections.Generic; -using System.Linq; +using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -using System.Text; -using System.Threading.Tasks; using Windows.Win32; +using Windows.Win32.Foundation; +using Windows.Win32.UI.WindowsAndMessaging; namespace CommunityToolkit.WinUI.HelpersRns; #if WINAPPSDK - internal class ThemeListenerHelperWindow { public delegate void ThemeChangedHandler(ApplicationTheme theme); public static ThemeListenerHelperWindow Instance = new(); - private static string s_className = "ThemeListenerHelperWindow"; - private IntPtr m_hwnd; + public event ThemeChangedHandler? ThemeChanged; - delegate Windows.Win32.Foundation.LRESULT WndProc(Windows.Win32.Foundation.HWND hWnd, uint msg, Windows.Win32.Foundation.WPARAM wParam, Windows.Win32.Foundation.LPARAM lParam); - private WndProc m_wnd_proc_delegate; - private void registerClass() + + private static string s_className = "ThemeListenerHelperWindow"; + + private HWND m_hwnd; + + private ThemeListenerHelperWindow() { - unsafe + s_className = "ThemeListenerHelperWindow"; + RegisterClass(); + m_hwnd = CreateWindow(); + } + + private static unsafe void RegisterClass() + { + WNDCLASSEXW wcx = default; + wcx.cbSize = (uint)sizeof(WNDCLASSEXW); + fixed (char* pClassName = s_className) { - var wcx = new Windows.Win32.UI.WindowsAndMessaging.WNDCLASSEXW(); - wcx.cbSize = (uint)Marshal.SizeOf(wcx); - fixed (char* pClassName = s_className) - { - wcx.lpszClassName = new Windows.Win32.Foundation.PCWSTR(pClassName); - } - wcx.lpfnWndProc = wndProc; - if (PInvoke.RegisterClassEx(in wcx) == 0) + wcx.lpszClassName = pClassName; + wcx.lpfnWndProc = &WndProc; + if (PInvoke.RegisterClassEx(in wcx) is 0) { - Debug.WriteLine(new Win32Exception(Marshal.GetLastWin32Error()).Message); + Marshal.ThrowExceptionForHR(Marshal.GetLastPInvokeError()); } } - } - static Windows.Win32.Foundation.LRESULT wndProc(Windows.Win32.Foundation.HWND hWnd, uint msg, Windows.Win32.Foundation.WPARAM wParam, Windows.Win32.Foundation.LPARAM lParam) + private static unsafe HWND CreateWindow() { - switch (msg) + HWND hwnd = PInvoke.CreateWindowEx(0, s_className, string.Empty, 0, 0, 0, 0, 0, default, null, null, null); + if (hwnd == HWND.Null) { - case PInvoke.WM_SETTINGCHANGE: - var value = Registry.GetValue( - """HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize""", - "AppsUseLightTheme", - true - ); - if (value != null) - { - Instance.ThemeChanged?.Invoke((int)value == 1 ? ApplicationTheme.Light : ApplicationTheme.Dark); - } - break; + Marshal.ThrowExceptionForHR(Marshal.GetLastPInvokeError()); } - return PInvoke.DefWindowProc(hWnd, msg, wParam, lParam); + return hwnd; } - unsafe private static IntPtr createWindow() + [UnmanagedCallersOnly(CallConvs = [typeof(CallConvStdcall)])] + private static LRESULT WndProc(HWND hWnd, uint msg, WPARAM wParam, LPARAM lParam) { - var hwnd = PInvoke.CreateWindowEx( - 0, - s_className, - "", - 0, - 0, 0, 0, 0, - new Windows.Win32.Foundation.HWND(), - null, - null, - null); - if (hwnd == IntPtr.Zero) + if (msg is PInvoke.WM_SETTINGCHANGE) { - Debug.WriteLine(new Win32Exception(Marshal.GetLastWin32Error()).Message); + // REG_DWORD + object? value = Registry.GetValue( + @"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize", + "AppsUseLightTheme", + true); + + if (value is int dword) + { + Instance.ThemeChanged?.Invoke(dword is 1 ? ApplicationTheme.Light : ApplicationTheme.Dark); + } } - return hwnd; - } - private ThemeListenerHelperWindow() - { - m_wnd_proc_delegate = wndProc; - s_className = "ThemeListenerHelperWindow"; - registerClass(); - m_hwnd = createWindow(); + + return PInvoke.DefWindowProc(hWnd, msg, wParam, lParam); } } #endif From 1cd0f4b9c0bcc12730c94b4fac791a51bea2504f Mon Sep 17 00:00:00 2001 From: DismissedLight <1686188646@qq.com> Date: Mon, 30 Sep 2024 13:35:37 +0800 Subject: [PATCH 4/5] apply suggestion --- .../Helpers/src/CommunityToolkit.WinUI.Helpers.csproj | 3 --- components/Helpers/src/NativeMethods.json | 8 +++++++- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/components/Helpers/src/CommunityToolkit.WinUI.Helpers.csproj b/components/Helpers/src/CommunityToolkit.WinUI.Helpers.csproj index 8157235a..76f50f8f 100644 --- a/components/Helpers/src/CommunityToolkit.WinUI.Helpers.csproj +++ b/components/Helpers/src/CommunityToolkit.WinUI.Helpers.csproj @@ -30,7 +30,4 @@ - - - diff --git a/components/Helpers/src/NativeMethods.json b/components/Helpers/src/NativeMethods.json index 9725d209..be639985 100644 --- a/components/Helpers/src/NativeMethods.json +++ b/components/Helpers/src/NativeMethods.json @@ -1,3 +1,9 @@ { - "allowMarshaling": false + "$schema": "https://aka.ms/CsWin32.schema.json", + "allowMarshaling": false, + "comInterop": { + "preserveSigMethods": [ + "*" + ] + } } From 4586dee7660c6cb83340fc557d3937a40c1e2e1b Mon Sep 17 00:00:00 2001 From: HO-COOH Date: Mon, 30 Sep 2024 16:29:36 +0800 Subject: [PATCH 5/5] Revert EOF in MultiTarget.props