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

WinAPI C++编辑控件异常:编写修改窗口标题程序遇问题

Fixing Your WinAPI Edit Control & Window Title Update Issue

Hey there! Let's figure out why your Edit control isn't working and get that window title update feature up and running smoothly. Based on what you shared, here are the most common pitfalls and a corrected version of your code:

Common Issues to Check

  • Missing Edit Control Styles: Your Edit control needs essential styles like WS_CHILD and WS_VISIBLE to render properly, plus useful ones like ES_AUTOHSCROLL for handling long text.
  • Unassigned hEdit Handle: If your global hEdit variable isn't set when creating the Edit control, calls to GetWindowText will fail silently.
  • No Message Handling for Input: You need to listen for events (like a button click or Edit content change) to trigger the window title update.

Corrected Full Code

#include <Windows.h>

LRESULT CALLBACK WindowProcedure(HWND, UINT, WPARAM, LPARAM);
void AddControl(HWND);

HWND hEdit;
#define IDC_EDIT 1001  // Unique ID for our Edit control

int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrewInst, LPSTR args, int ncmdshow) {
    WNDCLASSW wc = { 0 };
    wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);  // +1 avoids system brush access issues
    wc.hCursor = LoadCursor(NULL, IDC_ARROW);
    wc.hInstance = hInst;
    wc.lpszClassName = L"WinAPITestClass";
    wc.lpfnWndProc = WindowProcedure;

    // Register window class with error checking
    if (!RegisterClassW(&wc)) {
        MessageBox(NULL, L"Window Registration Failed!", L"Error!", MB_ICONEXCLAMATION | MB_OK);
        return 0;
    }

    // Create main window
    HWND hWnd = CreateWindowW(L"WinAPITestClass", L"Default Window Title", 
        WS_OVERLAPPEDWINDOW | WS_VISIBLE,
        CW_USEDEFAULT, CW_USEDEFAULT, 400, 200, NULL, NULL, hInst, NULL);

    if (hWnd == NULL) {
        MessageBox(NULL, L"Window Creation Failed!", L"Error!", MB_ICONEXCLAMATION | MB_OK);
        return 0;
    }

    AddControl(hWnd);  // Initialize our Edit control and trigger button

    // Message loop to keep the window running
    MSG msg;
    while (GetMessage(&msg, NULL, 0, 0) > 0) {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    return msg.wParam;
}

void AddControl(HWND hWnd) {
    // Create Edit control with proper styles and assign to global hEdit
    hEdit = CreateWindowW(L"EDIT", L"Enter new title here...", 
        ES_LEFT | ES_AUTOHSCROLL | WS_BORDER | WS_VISIBLE | WS_CHILD,
        20, 20, 340, 25, hWnd, (HMENU)IDC_EDIT, GetModuleHandle(NULL), NULL);
    
    if (hEdit == NULL) {
        MessageBox(hWnd, L"Edit Control Creation Failed!", L"Error!", MB_ICONEXCLAMATION | MB_OK);
    }

    // Add a button to manually trigger title update (user-friendly touch)
    CreateWindowW(L"BUTTON", L"Update Title", 
        BS_PUSHBUTTON | WS_VISIBLE | WS_CHILD,
        150, 60, 100, 30, hWnd, (HMENU)1002, GetModuleHandle(NULL), NULL);
}

LRESULT CALLBACK WindowProcedure(HWND hWnd, UINT msg, WPARAM wp, LPARAM lp) {
    switch (msg) {
        case WM_COMMAND:
            // Handle button click to update window title
            if (LOWORD(wp) == 1002) {
                wchar_t titleBuffer[256];
                GetWindowTextW(hEdit, titleBuffer, sizeof(titleBuffer)/sizeof(wchar_t));
                SetWindowTextW(hWnd, titleBuffer);
            }
            // Optional: Auto-update title as the user types in the Edit control
            else if (LOWORD(wp) == IDC_EDIT && HIWORD(wp) == EN_CHANGE) {
                wchar_t titleBuffer[256];
                GetWindowTextW(hEdit, titleBuffer, sizeof(titleBuffer)/sizeof(wchar_t));
                SetWindowTextW(hWnd, titleBuffer);
            }
            break;
        case WM_DESTROY:
            PostQuitMessage(0);
            break;
        default:
            return DefWindowProcW(hWnd, msg, wp, lp);
    }
    return 0;
}

Key Fixes Explained

  1. Proper Edit Control Setup: We added all required styles and assigned the returned handle to hEdit, so we can reliably access the control later.
  2. Event-Driven Updates: The WM_COMMAND message listens for both button clicks and Edit content changes, using GetWindowTextW to fetch input and SetWindowTextW to update the window title.
  3. Error Checking: Added checks for window/class registration failures to catch issues early instead of letting them cause silent crashes.
  4. Unicode Compatibility: Used W-suffixed WinAPI functions to handle wide characters correctly, avoiding messy encoding bugs.

Give this code a try—your Edit control should now work as expected, and typing in it (or clicking the button) will update the window title in real time!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:43:08