Mouse Click Example
#include <windows.h>
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
int WINAPI WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
const wchar_t CLASS_NAME[] = L"MyWindowClass";
WNDCLASSEXW wc = {0};
MSG msg;
// Register the window class
wc.cbSize = sizeof(WNDCLASSEXW);
wc.lpfnWndProc = WndProc;
wc.hInstance = hInstance;
wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = GetSysColorBrush(COLOR_WINDOW);
wc.lpszClassName = CLASS_NAME;
wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
if (!RegisterClassExW(&wc))
return 0;
HWND hwnd = CreateWindowExW(
WS_EX_CLIENTEDGE,
CLASS_NAME,
L"Mouse Click Demo",
WS_OVERLAPPEDWINDOW | WS_VISIBLE,
CW_USEDEFAULT,
CW_USEDEFAULT,
700,
200,
NULL,
NULL,
hInstance,
NULL);
if (!hwnd)
return 0;
// Message loop
while (GetMessage(&msg, NULL, 0, 0) > 0)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return static_cast<int>(msg.wParam);
}
LRESULT CALLBACK WndProc(HWND hwnd,
UINT message,
WPARAM wParam,
LPARAM lParam)
{
static wchar_t mouseStr[255] = L"";
static int xPos = 0;
static int yPos = 0;
switch (message)
{
case WM_LBUTTONDOWN:
xPos = LOWORD(lParam);
yPos = HIWORD(lParam);
if (wParam & MK_SHIFT)
{
wsprintfW(mouseStr,
L"Shift + Left Button Down at %d,%d",
xPos, yPos);
}
else if (wParam & MK_CONTROL)
{
wsprintfW(mouseStr,
L"Ctrl + Left Button Down at %d,%d",
xPos, yPos);
}
else if (wParam & MK_RBUTTON)
{
wsprintfW(mouseStr,
L"Left and Right Buttons Down at %d,%d",
xPos, yPos);
}
else
{
wsprintfW(mouseStr,
L"Left Button Down at %d,%d",
xPos, yPos);
}
InvalidateRect(hwnd, NULL, TRUE);
return 0;
case WM_LBUTTONUP:
xPos = LOWORD(lParam);
yPos = HIWORD(lParam);
wsprintfW(mouseStr,
L"Left Button Up at %d,%d",
xPos, yPos);
InvalidateRect(hwnd, NULL, TRUE);
return 0;
case WM_RBUTTONDOWN:
xPos = LOWORD(lParam);
yPos = HIWORD(lParam);
wsprintfW(mouseStr,
L"Right Button Down at %d,%d",
xPos, yPos);
InvalidateRect(hwnd, NULL, TRUE);
return 0;
case WM_RBUTTONUP:
xPos = LOWORD(lParam);
yPos = HIWORD(lParam);
wsprintfW(mouseStr,
L"Right Button Up at %d,%d",
xPos, yPos);
InvalidateRect(hwnd, NULL, TRUE);
return 0;
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd, &ps);
TextOutW(hdc,
xPos,
yPos,
mouseStr,
lstrlenW(mouseStr));
EndPaint(hwnd, &ps);
return 0;
}
case WM_DESTROY:
PostQuitMessage(0);
return 0;
}
return DefWindowProcW(hwnd,
message,
wParam,
lParam);
}