<知识分享>
上次讲的是键盘事件,这次我们介绍鼠标事件。下面先介绍下鼠标事件的结构体以及相关信息。
- typedef struct _MOUSE_EVENT_RECORD
- {
- COORD dwMousePosition;
- DWORD dwButtonState;
- DWORD dwControlKeyState;
- DWORD dwEventFlags;
- } MOUSE_EVENT_RECORD;
下面给一个样例程序,实现在控制台窗口缓冲区的最下面一行显示当前鼠标在缓冲区的坐标,单击左键在当前鼠标位置输出字母A,单击右键则输出字母B,双击任何鼠标键退出的功能。程序如下:
- #include <stdio.h>
- #include <windows.h>
- #include <conio.h>
-
- HANDLE handle_in;
- HANDLE handle_out;
- CONSOLE_SCREEN_BUFFER_INFO csbi;
-
- void DisplayMousePosition(COORD pos);
-
- void gotoxy(int x, int y);
-
- int main()
- {
- handle_in = GetStdHandle(STD_INPUT_HANDLE);
- handle_out = GetStdHandle(STD_OUTPUT_HANDLE);
- INPUT_RECORD mouserec;
- DWORD res;
- COORD pos;
- COORD size = {80, 25};
- GetConsoleScreenBufferInfo(handle_out, &csbi);
- SetConsoleScreenBufferSize(handle_out, size);
- for (;;)
- {
- ReadConsoleInput(handle_in, &mouserec, 1, &res);
- pos = mouserec.Event.MouseEvent.dwMousePosition;
- gotoxy(0, 24);
- DisplayMousePosition(pos);
- if (mouserec.EventType == MOUSE_EVENT)
- {
- gotoxy(pos.X, pos.Y);
-
- if (mouserec.Event.MouseEvent.dwButtonState == FROM_LEFT_1ST_BUTTON_PRESSED)
- {
- putchar(‘A‘);
- }
-
- if (mouserec.Event.MouseEvent.dwButtonState == RIGHTMOST_BUTTON_PRESSED)
- {
- putchar(‘B‘);
- }
-
- if (mouserec.Event.MouseEvent.dwEventFlags == DOUBLE_CLICK)
- {
- break;
- }
- }
- }
- CloseHandle(handle_out);
- CloseHandle(handle_in);
- return 0;
- }
-
- void DisplayMousePosition(COORD pos)
- {
- COORD dis = {0, 24};
- WORD att = FOREGROUND_GREEN | FOREGROUND_INTENSITY;
- GetConsoleScreenBufferInfo(handle_out, &csbi);
- printf("X = %3d, Y = %3d", (int)pos.X, (int)pos.Y);
- FillConsoleOutputAttribute(handle_out, att, 16, dis, NULL);
- return;
- }
-
- void gotoxy(int x, int y)
- {
- COORD pos = {x, y};
- SetConsoleCursorPosition(handle_out, pos);
- }
附上用本程序写的Hello world!的图:
C语言控制台窗口图形界面编程(八):鼠标事件,布布扣,bubuko.com
C语言控制台窗口图形界面编程(八):鼠标事件
原文:http://www.cnblogs.com/lxl0928/p/3807262.html