0

In a WPF applicaiton, creating a native window using User32 API, while configuring the WindowStyle with '~WindowStyles.WS_BORDER', the mouse messages can not be fired in the WndProc handler function.

How should I do so that the window has no borders and can capture mouse messages?

Some key codes are as follows:

using PInvoke;
using static PInvoke.User32;

unsafe
{
    IntPtr WndProc(IntPtr hWnd, WindowMessage msg, void* wParam, void* lParam)
    {
        Debug.WriteLine(msg);

        switch (msg)
        {
            case WindowMessage.WM_PAINT:
                break;
            case WindowMessage.WM_LBUTTONDOWN:
                // Can not been reached while WindowStyle configured with ~WindowStyles.WS_BORDER
                break;
            case WindowMessage.WM_DESTROY:
                PostQuitMessage(0);
                DestroyWindow(hWnd);
                break;

            default:
                break;
        }

        return DefWindowProc(hWnd, msg, (IntPtr)wParam, (IntPtr)lParam);
    }

    string className = "My_Window_Class_Name";
    IntPtr classNamePtr = Marshal.StringToHGlobalAuto(className);

    WNDCLASSEX wndClassEx = new WNDCLASSEX
    {
        cbSize = Marshal.SizeOf(typeof(WNDCLASSEX)),
        lpszClassName_IntPtr = classNamePtr,
        lpfnWndProc = new WndProc(ref WndProc)
    };

    short regResult = RegisterClassEx(ref wndClassEx);
    if (regResult == 0)
    {
        Win32ErrorCode error = Kernel32.GetLastError();
        Debug.WriteLine(error);
    }

    WindowStyles style = WindowStyles.WS_OVERLAPPEDWINDOW  | ~WindowStyles.WS_BORDER; // Here is the key factor causing the problem.
    WindowStylesEx styleEx = WindowStylesEx.WS_EX_TOPMOST;

    IntPtr window = CreateWindowEx(styleEx, className, "Window Title", style, 300,300, 300, 300, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
    if (window == (IntPtr)0)
    {

        Win32ErrorCode error = Kernel32.GetLastError();
        Debug.WriteLine(error);
    }

    ShowWindow(window, WindowShowStyle.SW_SHOWNORMAL);
    UpdateWindow(window);
}
Iron
  • 926
  • 1
  • 5
  • 16
  • 1
    `~WindowStyles.WS_BORDER` means, all styles except `WS_BORDER`. Your window probably has set `WS_POPUP`, `WS_CHILD`, and many other confusing styles. One of the styles set is `WS_DISABLED`, so window ignoreas user input. If you dont't want sizing border, start from `WS_POPUP` and add other flags that you need (with `|` operator). – Daniel Sęk Mar 04 '23 at 15:09

0 Answers0