更新时间:2015-12-28 15:28:33浏览次数:1+次
先来看看移动矩形的效果图:
【左击客户区时向右移动矩形,右击向下移动矩形】
#include "windows.h"
#include <tchar.h>
// - 项目是Unicode字符集
LRESULT CALLBACK WinProc(HWND hwnd,UINT message,WPARAM wParam,LPARAM lParam)
{
HDC hdc;
PAINTSTRUCT ps;
static RECT rect;
static int x=10;//每次x轴上移动的单位
static int y=10;//每次y轴上移动的单位
switch (message)
{
case WM_CREATE:
SetRect(&rect,0,0,100,100);//设置矩形的大小
return 0;
case WM_PAINT:
hdc = BeginPaint(hwnd,&ps);
SelectObject(hdc,GetStockObject(LTGRAY_BRUSH));
Rectangle(hdc,rect.left,rect.top,rect.right,rect.bottom);
EndPaint(hwnd,&ps);
return 0;
case WM_LBUTTONDOWN:
{
hdc=GetDC(hwnd);
if(!OffsetRect(&rect,x,0))//只计算和更新矩形位置
{
MessageBox(hwnd,_T("移动失败"),_T(""),0);
}
InvalidateRect(hwnd,NULL,TRUE);//让客户区绘制出移动后的矩形
ReleaseDC(hwnd,hdc);
}
return 0;
case WM_RBUTTONDOWN:
{
hdc=GetDC(hwnd);
if(!OffsetRect(&rect,0,y))//只计算和更新矩形位置
{
MessageBox(hwnd,_T("移动失败"),_T(""),0);
}
InvalidateRect(hwnd,NULL,TRUE);//让客户区绘制出移动后的矩形
ReleaseDC(hwnd,hdc);
}
return 0;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
default:
return DefWindowProc(hwnd, message, wParam, lParam);
}
}
int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrev,LPSTR lpCmd,int iShow)
{
TCHAR ClassName[] = _T("MyClass");
TCHAR title1[] = _T("C++技术网http://www.cjjjs.com");
WNDCLASS wndClass;
wndClass.cbClsExtra=0;
wndClass.cbWndExtra=0;
wndClass.hbrBackground= (HBRUSH)GetStockObject(WHITE_BRUSH);
wndClass.hCursor=LoadCursor(NULL,IDC_HAND);
wndClass.hIcon=LoadIcon(NULL,IDI_APPLICATION);
wndClass.hInstance = hInstance;
wndClass.lpfnWndProc = WinProc;
wndClass.lpszClassName = ClassName;
wndClass.lpszMenuName=NULL;
wndClass.style=CS_HREDRAW|CS_VREDRAW;
if(!RegisterClass(&wndClass))return 0;
HWND hwnd = CreateWindow(ClassName,title1,WS_OVERLAPPEDWINDOW,0,0,440,400,NULL,NULL,hInstance,NULL);
ShowWindow(hwnd,SW_SHOWNORMAL);
MSG msg;
while (GetMessage(&msg,NULL,0,0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}
相关资讯