#include <windows.h>
#include <cstdio>//sprintf
LRESULT CALLBACK WndProc(HWND hwnd,UINT message,WPARAM wParam,LPARAM lParam);
void test_draw_filled_rect(HDC hdc,int x1,int y1,int x2,int y2,COLORREF color)
{
RECT rc={x1,y1,x2,y2};
FillRect(hdc,&rc,CreateSolidBrush(color));
}
void test_draw_line(HDC hdc, int x1, int y1, int x2, int y2, COLORREF color)
{
HPEN hPen = CreatePen(PS_SOLID, 1, color);
HPEN hOldPen = static_cast<HPEN>(SelectObject(hdc, hPen));
MoveToEx(hdc, x1, y1, NULL);
LineTo(hdc, x2, y2);
SelectObject(hdc, hOldPen);
DeleteObject(hPen);
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
WNDCLASS wc={0};
wc.style=CS_HREDRAW|CS_VREDRAW;
wc.lpfnWndProc=WndProc;
wc.hInstance=hInstance;
wc.hbrBackground=(HBRUSH)(COLOR_WINDOW+1);
wc.lpszClassName="Color picker";
RegisterClassA(&wc);
HWND hwnd=CreateWindowA("Color picker","Color picker",WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,CW_USEDEFAULT,300,150,NULL,NULL,hInstance,NULL);
ShowWindow(hwnd,nCmdShow);
UpdateWindow(hwnd);
SetTimer(hwnd,1,1000,NULL);
MSG msg;
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}
LRESULT CALLBACK WndProc(HWND hwnd,UINT message,WPARAM wParam,LPARAM lParam)
{
switch(message)
{
case WM_PAINT:
{
RECT rect;
PAINTSTRUCT ps;
HDC hdc=BeginPaint(hwnd,&ps),hdc_screen=GetDC(NULL);
POINT pt;
GetCursorPos(&pt);
COLORREF color=GetPixel(hdc_screen,pt.x,pt.y);//获取屏幕上的像素
test_draw_filled_rect(hdc,0,0,30,30,color);//画出颜色,以供参考
ReleaseDC(NULL,hdc_screen);
GetClientRect(hwnd,&rect);
char str[114]={'\0'};
sprintf(str,"RGB:(%X,%X,%X) CursorPos:(%d,%d)",GetRValue(color),GetGValue(color),GetBValue(color),pt.x,pt.y);
DrawText(hdc,str,-1,&rect,DT_SINGLELINE|DT_CENTER|DT_VCENTER);
EndPaint(hwnd,&ps);
return 0;
}
case WM_TIMER://每一秒更新一次
{
InvalidateRect(hwnd,NULL,TRUE);
return 0;
}
case WM_DESTROY:
{
KillTimer(hwnd,1);
PostQuitMessage(0);
return 0;
}
}
return DefWindowProc(hwnd,message,wParam,lParam);
}