Saturday, January 31, 2009

How Do I Create a Window With Visual Styles?

The following code is a bare-bones application that loads a window with a button that creates a message box when pressed. It will enable visual styles on machines that support them. In order to get this to build in Visual Studio, create a new project, select "Win32 Console Application", then set the application type to "Windows Application" and check "Empty Project". In the project properties window, change Character Set to "Not Set" to disable unicode. The parts dealing with visual styles are highlighted in blue.


#pragma comment(lib, "comctl32.lib") // for visual styles
#pragma comment(linker, "/manifestdependency:\"type='win32' \
name='Microsoft.Windows.Common-Controls' version='6.0.0.0' \
processorArchitecture='*' publicKeyToken='6595b64144ccf1df' \
language='*'\"")

#include <windows.h>
#include <commctrl.h>
#define ID_OK 100

LRESULT CALLBACK MainWndProc(HWND hwnd, UINT uMsg,
WPARAM wParam, LPARAM lParam)
{
switch(uMsg)
{
case WM_COMMAND:
switch(LOWORD(wParam))
{
case ID_OK:
if(HIWORD(wParam) == BN_CLICKED)
MessageBox(hwnd, "OK Button Pressed",
"Notification", MB_OK);
break;
}
break;
case WM_CLOSE:
DestroyWindow(hwnd);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
}
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpszArgument, int nCmdShow)
{
MSG msg;
HWND hwnd;
WNDCLASSEX wcx = {0};

InitCommonControls(); // enable visual styles

wcx.cbSize = sizeof(wcx);
wcx.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
wcx.hCursor = LoadCursor(NULL, IDC_ARROW);
wcx.style = CS_HREDRAW | CS_VREDRAW;
wcx.lpszClassName = "MyWindowClass";
wcx.lpfnWndProc = MainWndProc;
wcx.hInstance = hInstance;
RegisterClassEx(&wcx);

hwnd = CreateWindowEx(WS_EX_CLIENTEDGE, "MyWindowClass",
"My Window Title", WS_VISIBLE | WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, 300, 200, NULL, NULL,
hInstance, NULL);

CreateWindow("BUTTON", "OK", WS_CHILD | WS_VISIBLE |
BS_PUSHBUTTON, 190, 120, 75, 25, hwnd, (HMENU)ID_OK,
hInstance, NULL);

while(GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}

return 0;
}