根据书上原代码,会出错,经本人纠正后正确代码如下:
// pro2.cpp : Defines the entry point for the application.
//
#include <stdafx.h>
#include <string>
//using namespace std
LRESULT CALLBACK WndProc(HWND hWnd,UINT message,WPARAM wParam,LPARAM lParam)
{
PAINTSTRUCT ps;
HDC hdc;
POINT pt;
CHAR szString[255];
switch(message)
{
case WM_PAINT:
hdc=BeginPaint(hWnd,&ps);
EndPaint(hWnd,&ps);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
case WM_MOUSEMOVE:
pt.x=LOWORD(lParam);
pt.y=HIWORD(lParam);
sprintf(szString,"[%d, %d]",pt.x,pt.y);
hdc=GetDC(hWnd);
TextOut(hdc,300,200,szString,strlen(szString));
ReleaseDC(hWnd,hdc);
default:
return DefWindowProc(hWnd,message,wParam,lParam);
}
return 0;
}
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=LoadIcon(hInstance,(LPCTSTR)IDI_APPLICATION);
wcex.hCursor=LoadCursor(NULL,IDC_ARROW);
wcex.hbrBackground=(HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName=NULL;
wcex.lpszClassName="MouseMove";
wcex.hIconSm=LoadIcon(wcex.hInstance,(LPCTSTR)IDI_HAND);
return RegisterClassEx(&wcex);
}
BOOL InitInstance(HINSTANCE hInstance,int nCmdShow)
{
HWND hWnd;
// hInst=hInstance;
hWnd=CreateWindow("MouseMove","实时鼠标位置",WS_OVERLAPPEDWINDOW,CW_USEDEFAULT,0,CW_USEDEFAULT,0,NULL,NULL,hInstance,NULL);
if(!hWnd)
{
return FALSE;
}
ShowWindow(hWnd,nCmdShow);
UpdateWindow(hWnd);
return TRUE;
}
int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
// TODO: Place code here.
MSG msg;
MyRegisterClass(hInstance);
if(!InitInstance(hInstance,nCmdShow))
{
return FALSE;
}
while(GetMessage(&msg,NULL,0,0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}
结果如下:
出错原因:
1:函数需先声明,后调用
2:sprintf()函数需用到string头文件
3:// hInst=hInstance;定义的全局变量在本例程中没有用到,且没有声明,故出错,删除之。
实现流程:
WinMain函数定义--->创建一个窗口--->进行消息循环--->编写窗口过程函数