Skip to content

Instantly share code, notes, and snippets.

@luojunyuan
Created April 22, 2026 16:50
Show Gist options
  • Select an option

  • Save luojunyuan/1ee5a9cc0cbbdf4bcab8de94ecd01bfc to your computer and use it in GitHub Desktop.

Select an option

Save luojunyuan/1ee5a9cc0cbbdf4bcab8de94ecd01bfc to your computer and use it in GitHub Desktop.
最标称的 csharp win32 窗口
using System;
using System.Runtime.InteropServices;
using Windows.Win32;
using Windows.Win32.Foundation;
using Windows.Win32.Graphics.Gdi;
using Windows.Win32.UI.WindowsAndMessaging;
internal static unsafe class App
{
private const string ClassName = "AppCoreApplication_MainWnd";
private const string WindowTitle = "AppCoreApplication";
// 保持 WndProc 委托存活,避免被 GC 回收导致 native 回调时崩溃。
private static readonly WNDPROC s_wndProc = WndProc;
[STAThread]
private static int Main()
{
using var hModule = PInvoke.GetModuleHandle((string?)null);
fixed (char* pClassName = ClassName)
{
WNDCLASSEXW wc = new()
{
cbSize = (uint)Marshal.SizeOf<WNDCLASSEXW>(),
lpfnWndProc = s_wndProc,
hInstance = (HINSTANCE)hModule.DangerousGetHandle(),
hCursor = PInvoke.LoadCursor(default, PInvoke.IDC_ARROW),
hbrBackground = (HBRUSH)(IntPtr)(COLOR_WINDOW + 1),
lpszClassName = pClassName,
};
if (PInvoke.RegisterClassEx(in wc) == 0)
{
return Marshal.GetLastPInvokeError();
}
}
HWND hwnd = PInvoke.CreateWindowEx(
dwExStyle: 0,
lpClassName: ClassName,
lpWindowName: WindowTitle,
dwStyle: WINDOW_STYLE.WS_OVERLAPPEDWINDOW,
X: PInvoke.CW_USEDEFAULT,
Y: PInvoke.CW_USEDEFAULT,
nWidth: PInvoke.CW_USEDEFAULT,
nHeight: PInvoke.CW_USEDEFAULT,
hWndParent: default,
hMenu: default,
hInstance: hModule,
lpParam: null);
if (hwnd.IsNull)
{
return Marshal.GetLastPInvokeError();
}
PInvoke.ShowWindow(hwnd, SHOW_WINDOW_CMD.SW_SHOW);
PInvoke.UpdateWindow(hwnd);
MSG msg;
while (PInvoke.GetMessage(out msg, default, 0, 0).Value > 0)
{
PInvoke.TranslateMessage(in msg);
PInvoke.DispatchMessage(in msg);
}
return (int)msg.wParam.Value;
}
private static LRESULT WndProc(HWND hwnd, uint msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
case PInvoke.WM_DESTROY:
PInvoke.PostQuitMessage(0);
return default;
}
return PInvoke.DefWindowProc(hwnd, msg, wParam, lParam);
}
private const int COLOR_WINDOW = 5;
}
RegisterClassExW
CreateWindowExW
DefWindowProcW
ShowWindow
UpdateWindow
GetMessageW
TranslateMessage
DispatchMessageW
PostQuitMessage
LoadCursorW
GetModuleHandleW
IDC_ARROW
CW_USEDEFAULT
WM_DESTROY
HBRUSH
@luojunyuan
Copy link
Copy Markdown
Author

cswin32 ping string 到 PCWSTR 必须要 fixed unsafe code 别想了

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment