During WPF program development, we often find that the default window title bar is too inappropriate and we want to modify its style. There are many ways to achieve this goal, but it is often not that easy. The simplest method is to directly create a new title bar in the form instead of the default title bar, so that we can fully use the well-known WPF development method. However, there is another problem, that is, the simulated title bar is not a real title bar after all. You can neither drag the window nor double-click to maximize it. Aland Li provides a good solution to this problem.
Windows uses the WM_NCHITTEST window message to determine the type of the mouse position. For example, if it is a title bar, we can capture the message and check the coordinates of the mouse. If it is within the title bar we designed, we will tell the system that this location is on the title bar (HTCAPTION (2) is returned )). The detailed code is as follows:
Private void Window_Loaded (object sender, RoutedEventArgs e ){// Add a message FilterIntPtr hwnd = new WindowInteropHelper (this ). handle; HwndSource. fromHwnd (hwnd ). addHook (new HwndSourceHook (WndProc);} private IntPtr WndProc (IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam,
Ref bool handled) {if (msg = WM_NCHITTEST ){// Obtain screen coordinatesPoint p = new Point (); int pInt = lParam. toInt32 (); p. X = (pInt <16)> 16; p. Y = pInt> 16; if (isOnTitleBar (PointFromScreen (p ))){// Cheat the system mouse over the title barHandled = true; return new IntPtr (2) ;}return IntPtr. Zero ;}private bool isOnTitleBar (Point p ){// Assume that the title bar is between 0 and 100.If (p. Y> = 0 & p. Y <100) return true; else return false;} private const int WM_NCHITTEST = 0x0084;
In this way, you can drag the window from the top of the window to the top of the window, or double-click the window to maximize the window.
To remove the default title bar, you only need to set WindowStyle to None.
BTW, in fact, does not necessarily require WPF. This method also applies to Winform, but generally, WPF programs have more requirements for beautifying the title bar.