一、重要函数
1.WORD LOWORD (DWORD dwValue);
function:返回低位字节,这里获取x坐标
2.WORD HIWORD (DWORD dwValue);
function:返回高位字节,这里获取y坐标
3.WINGDIAPI COLORREF WINAPI SetTextColor(HDC, COLORREF);
function:设置指定设备环境(DC)的字体颜色
4.
BOOL TextOut(
HDC hdc, // 设备描述表句柄
int nXStart, // 字符串的开始位置 x坐标
int nYStart, // 字符串的开始位置 y坐标
LPCTSTR lpString, // 字符串
int cbString // 字符串中字符的个数
);
二、实现代码
#include "stdafx.h"
#include <stdio.h>
HINSTANCE hInst;
ATOM MyRegisterClass(HINSTANCE hInstance);
BOOL InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
void MyPaint(HDC hdc,LPARAM lParam);
int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
MSG msg;
MyRegisterClass(hInstance);
if (!InitInstance (hInstance, nCmdShow))
{
return FALSE;
}
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}
ATOM MyRegisterClass(HINSTANCE hInstance)
{
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = (WNDPROC)WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = NULL;
wcex.hCursor = NULL;
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = NULL;
wcex.lpszClassName = "canvas";
wcex.hIconSm = NULL;
return RegisterClassEx(&wcex);
}
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
HWND hWnd;
hInst = hInstance;
hWnd = CreateWindow("canvas", "绘图窗口" , WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);
if (!hWnd)
{
return FALSE;
}
MoveWindow(hWnd,10,10,600,450,true);
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
return TRUE;
}
void MyPaint(HDC hdc,LPARAM lParam)
{
int x,y;
char str[20] = "";
x = LOWORD(lParam); //取得鼠标x坐标值
y = HIWORD(lParam); //取得鼠标y坐标值
SetTextColor(hdc,RGB(255,0,0));
TextOut(hdc,10,10,"鼠标坐标",strlen("鼠标坐标"));
sprintf(str,"X坐标%d ",x);//将格式化的数据写入字符串
TextOut(hdc,30,30,str,strlen(str));//在(30,30)处显示字符串
sprintf(str,"Y坐标%d ",y);
TextOut(hdc,30,50,str,strlen(str));
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
PAINTSTRUCT ps;//结构体包含了某应用程序用来绘制它所拥有的窗口客户区所需要的信息
HDC hdc;
switch (message)
{
case WM_PAINT:
hdc = BeginPaint(hWnd, &ps);
EndPaint(hWnd, &ps);
break;
case WM_MOUSEMOVE:
hdc = GetDC(hWnd);
MyPaint(hdc,lParam);
ReleaseDC(hWnd,hdc);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}