You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Windows API程序编译正常却无法运行:WinMain未执行问题

问题根源:程序入口冲突

你的程序同时定义了main(main.cpp)和WinMain(graphics.cpp),g++编译Windows程序时默认优先选择main作为程序入口,导致WinMain完全未执行——窗口根本没创建,调用DrawPixel自然看不到任何效果。

解决步骤

1. 统一程序入口

有两种方式解决入口冲突:

方式一:修改main.cpp,启动窗口消息循环

将main.cpp改为调用WinMain的逻辑,确保窗口初始化代码执行:

#include <windows.h>

// 声明WinMain
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInst, LPTSTR lpCmdLine, int nShowCmd);

int main() {
    // 获取当前程序实例句柄
    HINSTANCE hInstance = GetModuleHandle(NULL);
    // 调用WinMain启动窗口程序
    return WinMain(hInstance, NULL, GetCommandLine(), SW_SHOW);
}

方式二:编译时指定WinMain为入口

用g++编译时,添加参数指定入口为WinMainCRTStartup(Windows程序标准入口包装),同时加-mwindows隐藏控制台窗口:

g++ main.cpp graphics.cpp -o main -lgdi32 -mwindows -Wl,--entry=WinMainCRTStartup

2. 修复DrawPixel的潜在bug

除入口问题外,代码还有两处关键错误:

  • graphics.cpp中static HWND hwnd未被赋值,CreateWindowW返回的窗口句柄未存入该变量,导致DrawPixel里的hwnd始终为0;
  • DrawPixel使用BeginPaint/EndPaint仅适合在WM_PAINT消息处理中调用,其他场景应改用GetDC/ReleaseDC。

修改graphics.cpp的两处:

  1. 在CreateWindowW后保存窗口句柄:
hwnd = CreateWindowW(wc.lpszClassName, L"Pixels",
            WS_OVERLAPPEDWINDOW | WS_VISIBLE,
            100, 100, 300, 250, NULL, NULL, hInstance, NULL);
  1. 重写DrawPixel函数:
void DrawPixel(int x, int y) {
    if (hwnd == 0) return;

    HDC hdc = GetDC(hwnd);
    SetPixel(hdc, x, y, RGB(255, 0, 0));
    ReleaseDC(hwnd, hdc);
}

3. 可选:遵循Windows绘图规范(推荐)

如果要符合Windows的绘图机制,建议将绘制逻辑放到WM_PAINT消息处理中,避免窗口重绘后像素消失:

LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {
    switch(msg) {
        case WM_PAINT: {
            PAINTSTRUCT ps;
            HDC hdc = BeginPaint(hwnd, &ps);
            // 在WM_PAINT消息内绘制像素
            SetPixel(hdc, 100, 100, RGB(255, 0, 0));
            EndPaint(hwnd, &ps);
            break;
        }
        case WM_DESTROY:
            PostQuitMessage(0);
            return 0;
    }
    return DefWindowProcW(hwnd, msg, wParam, lParam);
}

内容的提问来源于stack exchange,提问作者Mason Cooreman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 11:10:40