《Visual C++开发入门与编程实践》之一:实时显示鼠标位置

根据书上原代码,会出错,经本人纠正后正确代码如下:

 

 

// 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函数定义--->创建一个窗口--->进行消息循环--->编写窗口过程函数

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值