/* -------------------------------------------------------------------
MyWindows.c -- 基本窗口模型
《Windows 程序设计(SDK)》视频教程
--------------------------------------------------------------------*/
#include <windows.h>
#include <strsafe.h>
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow)
{
static TCHAR szAppName[] = TEXT("MyWindows");//定义一个窗口类名字
HWND hwnd; //窗口句柄
MSG msg; //消息结构
WNDCLASS wndclass; //窗口类结构 //声明
wndclass.style = CS_HREDRAW | CS_VREDRAW ; //指定窗口类型
wndclass.lpfnWndProc = WndProc; //指定窗口过程
wndclass.cbClsExtra = 0; //预留的额外空间
wndclass.cbWndExtra = 0;
wndclass.hInstance = hInstance; //应用程序的实例句柄
wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);//为所有基于该窗口类设定一个图标
wndclass.hCursor = LoadCursor(NULL, IDC_ARROW); //为所有基于该窗口类设定一个鼠标指针
wndclass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);//指定窗口背景色
wndclass.lpszMenuName = NULL;//指定窗口菜单
wndclass.lpszClassName = szAppName;//指定窗口类名
if (!RegisterClass(&wndclass))//注册
{
MessageBox(NULL, TEXT("这个程序需要在 Windows NT 才能执行!"), szAppName, MB_ICONERROR);
return 0;
}
hwnd = CreateWindow(szAppName, //窗口类名称lpClassName
TEXT("颜色拾取器"), //窗口标题lpWindowName
WS_OVERLAPPEDWINDOW & ~WS_SIZEBOX, //窗口风格dwStyle 使其不能改变大小
CW_USEDEFAULT, //初始x坐标 CW CreatWindow创建窗口选项
CW_USEDEFAULT, //y
// CW_USEDEFAULT, //初始x方向尺寸nWidth
// CW_USEDEFAULT, //y nHeight
250,
100,//初始化窗口长宽
NULL, //父窗口句柄hWndParent
NULL, //窗口菜单句柄hMenu
hInstance, //程序实例句柄hInstance
NULL); //创建参数lpParam
ShowWindow(hwnd, iCmdShow); //显示窗口
UpdateWindow(hwnd); //更新窗口
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg); //翻译消息
DispatchMessage(&msg); //分配消息 调用
} //消息循环
return msg.wParam;
}
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
HDC hdc;
HDC hdc2;//DC:Device Context 设备环境
PAINTSTRUCT ps;
RECT rect;
static POINT apt;
static int R,G,B;
static COLORREF color;
TCHAR buffer[128];
switch (message)
{
case WM_CREATE:
SetTimer(hwnd,1,100,NULL);//100ms定时器
return 0;
case WM_PAINT: //绘制窗口
hdc2=GetDC(NULL); //获取屏幕DC
GetCursorPos(&apt); //获取屏幕坐标
color=GetPixel(hdc2,apt.x,apt.y);//拾取像素点
R=GetRValue(color);
G=GetGValue(color);
B=GetBValue(color); //获取RGB值
ReleaseDC(NULL,hdc2); //释放DC
hdc = BeginPaint(hwnd, &ps);
SetClassLongPtr(hwnd,GCLP_HBRBACKGROUND,(LONG)(CreateSolidBrush(RGB(R,G,B))));//设置背景颜色
SetTextColor(hdc,RGB(0,0,0)); //设置字体颜色
if(R<167&&G<167&&B<167)SetTextColor(hdc,RGB(255,255,255));
GetClientRect(hwnd, &rect); //获得客户区的位置坐标信息
SetBkMode(hdc,TRANSPARENT); //设置字体背景为透明
StringCchPrintf(buffer,128,TEXT("#%2X%2X%2X"),R,G,B);
DrawText(hdc, buffer, -1, &rect,DT_SINGLELINE | DT_CENTER | DT_VCENTER); //绘制文字 一行 居中 垂直居中 显示RGB值
EndPaint(hwnd, &ps);
return 0;
case WM_DESTROY: //窗口关闭
PostQuitMessage(0);
return 0;
case WM_TIMER:
InvalidateRect(hwnd,NULL,TRUE);//100ms刷新一次窗口
return 0;
}
if((message==WM_NCLBUTTONDOWN)&&(wParam==HTMAXBUTTON))return 0;//最大化失效
return DefWindowProc(hwnd, message, wParam, lParam);//windows处理其他消息
}