光标移动以及鼠标信息捕捉

此代码是将光标跳到指定位置。

gotoxy(x,y) x代表行,y代表列,下标是从0开始的


#include<iostream>
#include<windows.h>
#include<stdio.h>
#include<string.h>


using namespace std;


void gotoxy(int x,int y)//位置函数
{
    COORD pos;
    pos.X=y;
    pos.Y=x;
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),pos);
}
int main()
{
    cout<<"sssssssss"<<endl;
    gotoxy(0,1);
    getchar();
    return 0;
}



2.鼠标信息捕捉:

       在控制台程序中获取鼠标事件。


下面给出一个小程序


<span style="font-size:14px;">#include <windows.h>
#include <stdio.h>

int main(void)
{
    // 获取标准输入输出设备句柄
    HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
    HANDLE hIn = GetStdHandle(STD_INPUT_HANDLE);
    CONSOLE_SCREEN_BUFFER_INFO bInfo;
    INPUT_RECORD	mouseRec;
    DWORD			res;
    COORD			crPos, crHome = {0, 0};
    printf("[Cursor Position] X: %2lu  Y: %2lu\n", 0, 0);	// 初始状态
    while (1)
    {
        ReadConsoleInput(hIn, &mouseRec, 1, &res);
        if (mouseRec.EventType == MOUSE_EVENT)
        {
            if (mouseRec.Event.MouseEvent.dwButtonState==FROM_LEFT_1ST_BUTTON_PRESSED)
            {
                if (mouseRec.Event.MouseEvent.dwEventFlags == DOUBLE_CLICK)
                {
                    break;	// 左键双击 退出循环
                }
            }
            crPos = mouseRec.Event.MouseEvent.dwMousePosition;
            GetConsoleScreenBufferInfo(hOut, &bInfo);
            SetConsoleCursorPosition(hOut, crHome);
            printf("[Cursor Position] X: %2lu  Y: %2lu", crPos.X, crPos.Y);
            SetConsoleCursorPosition(hOut, bInfo.dwCursorPosition);
            switch (mouseRec.Event.MouseEvent.dwButtonState)
            {
            case FROM_LEFT_1ST_BUTTON_PRESSED:			// 左键 输出A
                FillConsoleOutputCharacter(hOut,'1', 1, crPos, &res);
                break;		// 如果使用printf输出,则之前需要先设置光标的位置
            case RIGHTMOST_BUTTON_PRESSED:				// 右键 输出a
                FillConsoleOutputCharacter(hOut,'2', 1, crPos, &res);
                break;
            default:
                break;
            }
        }
    }
    CloseHandle(hOut);  // 关闭标准输出设备句柄
    CloseHandle(hIn);   // 关闭标准输入设备句柄
    return 0;
}</span><span style="font-size:24px;">
</span>



posted @ 2016-05-13 17:51  Code-dream  阅读(463)  评论(0编辑  收藏  举报