SetWindowText
Sets the text of a window's title bar (if it has one). The function sends a WM_SETTEXT message to the specified window.
Syntax
C
BOOL SetWindowTextA(
HWND hWnd,
LPCSTR lpString
);
BOOL SetWindowTextW(
HWND hWnd,
LPCWSTR lpString
);
#ifdef UNICODE
#define SetWindowText SetWindowTextW
#else
#define SetWindowText SetWindowTextA
#endif
Parameters
| Parameter | Type | Description |
|---|---|---|
hWnd |
HWND |
Handle to the window whose text is to be changed. |
lpString |
LPCSTR or LPCWSTR |
Pointer to the null-terminated string to be set as the window's title. |
Return Value
Returns TRUE if the operation succeeds; otherwise, FALSE. Use GetLastError for extended error information.
Remarks
- The function updates the window's title bar. For child windows that do not have a title bar, the text may be used for accessibility or other purposes.
- If the window is a control, the text may be used as the control's label (e.g., button text).
- This function sends a
WM_SETTEXTmessage which may be intercepted by the window procedure.
Note: In Unicode builds, use
SetWindowTextW. In ANSI builds, use SetWindowTextA. The SetWindowText macro resolves automatically.
Example
C
#include <windows.h>
int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInst, LPSTR lpCmdLine, int nCmdShow)
{
HWND hWnd = CreateWindowEx(
0,
L"STATIC",
L"Initial Title",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, 400, 200,
NULL, NULL, hInst, NULL);
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
// Change the window title after 2 seconds
Sleep(2000);
SetWindowTextW(hWnd, L"New Title Set by SetWindowText");
MSG msg;
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return (int)msg.wParam;
}