/*============================================================================
Name : Exercise.cpp
Author : Haier
Version : 1.01
Copyright : Copyright (c) 2014
Description : Consele Mouse program in C, Ansi-style, Compile by Code:Block
============================================================================*/
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
int main(int argc,char *argv[])
{
DWORD dwMode,dwOldMode; /* 原来的模式与新模式 */
HANDLE hStdin,hStdout; /* 标准输入输出句柄 */
CONSOLE_CURSOR_INFO ms,msOld;
INPUT_RECORD InPut[128]; /* 控制台输入记录 */
DWORD dwEnent; /* 已经读取的输入事件数 */
UINT Count;
COORD MsPos; /* 鼠标移动时更新坐标 */
int Position;
if(argc==2 && argv[1][0]=='/' && argv[1][1]=='\?')
{
printf( "使用方法:\n"
"\t/\?\t查看帮助\n\n"
"返回值处理:\n"
"\t%%ERRORLEVEL%% 高 16 位包含鼠标 X 坐标\n"
"\t%%ERRORLEVEL%% 低 16 位包含鼠标 Y 坐标\n"
"比如:返回 65537, 可以用如下方式取得 X,Y\n"
"\tset /a ret=%%errorlevel%%\n"
"\tset /a \"x=%%ret%%>>16\"\n"
"\tset /a \"y=%%ret%%&65535\"\n\n");
exit(1);
}
/* 取得输入输出句柄 */
hStdin =GetStdHandle(STD_INPUT_HANDLE);
hStdout=GetStdHandle(STD_OUTPUT_HANDLE);
/* 取得并设置控制台模式 */
if(!GetConsoleMode(hStdin,&dwOldMode))
{
fprintf(stderr,"GetConsoleMode error: %s",GetLastError());
exit(1);
}
dwMode=dwOldMode | ENABLE_WINDOW_INPUT | ENABLE_MOUSE_INPUT;
if(!SetConsoleMode(hStdin,dwMode))
{
fprintf(stderr,"SetConsoleMode error: %s",GetLastError());
exit(1);
}
/* 取得并设置鼠标模式 */
if(!GetConsoleCursorInfo(hStdout,&msOld))
{
fprintf(stderr,"GetConsoleCursorInfo error: %s",GetLastError());
exit(1);
}
ms.dwSize =100;
ms.bVisible =TRUE;
if(!SetConsoleCursorInfo(hStdout,&ms))
{
fprintf(stderr,"SetConsoleCursorInfo error: %s",GetLastError());
exit(1);
}
while(1)
{
if(!ReadConsoleInput(hStdin,InPut,128,&dwEnent))
{
fprintf(stderr,"ReadConsoleInput error: %s",GetLastError());
exit(1);
}
for(Count=0; Count<dwEnent; Count++)
{
switch(InPut[Count].EventType)
{
case MOUSE_EVENT:
{
switch(InPut[Count].Event.MouseEvent.dwEventFlags)
{
case 0: /* 取得鼠标单击事件 */
{
if(InPut[Count].Event.MouseEvent.dwButtonState==FROM_LEFT_1ST_BUTTON_PRESSED)
{
SetConsoleMode(hStdin,dwOldMode);
SetConsoleCursorInfo(hStdin,&msOld);
Position=InPut[Count].Event.MouseEvent.dwMousePosition.X;
Position=Position<<16 | InPut[Count].Event.MouseEvent.dwMousePosition.Y;
return Position;
}
break;
}
case MOUSE_MOVED: /* 更新鼠标位置 */
{
MsPos.X=InPut[Count].Event.MouseEvent.dwMousePosition.X;
MsPos.Y=InPut[Count].Event.MouseEvent.dwMousePosition.Y;
SetConsoleCursorPosition(hStdout,MsPos);
break;
}
}
}
default:
{
break;
}
}
}
}
}