windows下控制鼠标移动和点击的c语言实现

最近由于老婆工作上有抢单的需求,需要一款自动处理鼠标事件的小程序,之前也没有编写过直接操作系统资源的程序,所以一开始是

打算用python来写,毕竟脚本语言实现起来方便,可是后来实施起来发现需要安装很多库,而且有些库就是怎么都安装不上大哭,于是就放

弃了。后来查阅了一些资料,看了很多别人写的博客,发现用C#和mfc实现的比较多,mfc这东西我本身就不感兴趣,果断放弃,倒是C#吸

引了我,但是发现新买的电脑还没有装Visual Studio,而且我又比较懒,只能放弃了,最后决定用VC控制台程序来实现。其实这个程序实现

的关键就是调用windows api中的user32.dll中的两个函数就搞定了,这里要特别感谢一篇不知作者的文章,给了我提示,文章的链接是

http://www.2cto.com/kf/201410/343342.html。废话不多说,直接上代码。以下是代码中的两个关键函数封装,完整可运行代码请到

http://download.csdn.net/detail/zjuman2007/9922444下载。


//this macro already defined
//const int MOUSEEVENTF_MOVE = 0x0001;      //移动鼠标
//const int MOUSEEVENTF_LEFTDOWN = 0x0002;  //模拟鼠标左键按下 
//const int MOUSEEVENTF_LEFTUP = 0x0004;    //模拟鼠标左键抬起 
//const int MOUSEEVENTF_RIGHTDOWN = 0x0008; //模拟鼠标右键按下 
//const int MOUSEEVENTF_RIGHTUP = 0x0010;   //模拟鼠标右键抬起 
//const int MOUSEEVENTF_MIDDLEDOWN = 0x0020;//模拟鼠标中键按下 
//const int MOUSEEVENTF_MIDDLEUP = 0x0040;  //模拟鼠标中键抬起 
//const int MOUSEEVENTF_ABSOLUTE = 0x8000;  //标示是否采用绝对坐标

/** mouse move
 * x -- int, x-coordinate
 * y -- int, y-coordinate
 */
int move(int x, int y){
	HINSTANCE hDll;  
	typedef bool (*Fun1)(int,int);
	hDll = LoadLibrary("user32.dll");
	if(NULL == hDll)  
  {  
  	fprintf(stderr, "load dll 'user32.dll' fail.");  
    return -1;  
  }
  
  Fun1 SetCursorPos = (Fun1)GetProcAddress(hDll, "SetCursorPos");  
  if(NULL == SetCursorPos)  
  {  
  	fprintf(stderr, "call function 'SetCursorPos' fail.");  
    FreeLibrary(hDll);  
    return -1;  
  }
  SetCursorPos(x,y);
  FreeLibrary(hDll);  
  return 0;
}

/** mouse click
 * type          -- int, 0:left click;1:right click 
 * double_click  -- bool, true:double click; false: single click
 */
int click(int type,bool double_click){
	int left_click = MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP;
	int right_click = MOUSEEVENTF_RIGHTDOWN | MOUSEEVENTF_RIGHTUP;
	int clicktype;
	HINSTANCE hDll;  
	typedef void (*Fun2)(
			DWORD dwFlags,        // motion and click options
			DWORD dx,             // horizontal position or change
			DWORD dy,             // vertical position or change
			DWORD dwData,         // wheel movement
			ULONG_PTR dwExtraInfo // application-defined information
	);

	hDll = LoadLibrary("user32.dll");
	if(NULL == hDll)  
  {  
  	fprintf(stderr, "load dll 'user32.dll' fail.");  
    return -1;  
  }
  
  Fun2 mouse_event = (Fun2)GetProcAddress(hDll, "mouse_event");  
  if(NULL == mouse_event)  
  {  
  	fprintf(stderr, "call function 'mouse_event' fail.");  
    FreeLibrary(hDll);  
    return -1;  
  }
  if(type==0)
  	clicktype = left_click;
  else
  	clicktype = right_click;
  mouse_event (clicktype, 0, 0, 0, 0 );
	FreeLibrary(hDll);
	if(double_click)
		click(type,false);
  return 0;
}


你可能感兴趣的:(windows,C语言)