WNDCLASSEX 结构中最少需要的信息是什么?

问题描述 投票:0回答:1

我正在尝试调用

RegisterClassEx
,并且我需要生成一个
WNDCLASSEX
结构。该结构的最低要求是什么?

在本示例中,我使用 C# 和 CsWin32 来生成 PInvoke 绑定。

c# .net windows winapi
1个回答
0
投票

通过实验和阅读

WNDCLASSEX
的文档,所需的项目是:

  • cbSize
  • hInstance
  • lpfnWndProc
  • lpszClassName
    (除非你使用原子?)

另外,您几乎肯定会想要:

  • hbrBackground
    - 或者当您调整窗口大小时,背景的新部分将简单地绘制为黑色
  • hCursor
    - 或者光标将保持进入屏幕时的状态(例如调整大小箭头)

请注意,这利用了默认初始化的优点——大多数其他参数接受

0
(“null”),因此它们的行为正确。如果不能保证该内存被清零,则会出现未定义的行为。在这种情况下,可能需要每个参数。


// Adapted from my personal code & 
// https://github.com/microsoft/CsWin32/blob/99ddd314ea359d3a97afa82c735b6a25eb25ea32/test/WinRTInteropTest/Program.cs
const string WindowClassName = "SimpleWindow";
WNDPROC WndProc = (hwnd, msg, wParam, lParam) =>
{
     return WndProc(hwnd, msg, wParam, lParam);
};

unsafe
{
    fixed (char* pClassName = WindowClassName)
    {
        var wndClass = new WNDCLASSEXW
        {
            // You need to include the size of this struct.
            cbSize = (uint)Marshal.SizeOf<WNDCLASSEXW>(),

            // Otherwise, when you resize this, the window will not paint the
            // new areas.
            hbrBackground = new HBRUSH((nint)SYS_COLOR_INDEX.COLOR_WINDOW + 1),

            // Otherwise, the mouse cursor will remain whatever it was when it
            // entered your HWND (e.g. resize arrows).
            hCursor = PInvoke.LoadCursor(HINSTANCE.Null, PInvoke.IDC_ARROW),

            // Seems to work without this, but it seems sketchy to leave it out.
            hInstance = PInvoke.GetModuleHandle(default(PCWSTR)),

            // Required to actually run your WndProc (and the app will crash if
            // null).
            lpfnWndProc = WndProc,

            // Required to identify the window class in CreateWindowEx.
            lpszClassName = pClassName,
        };

        PInvoke.RegisterClassEx(wndClass);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.