C语言中一些常用的控制台的API使用方法
控制台窗口设置system("title XXX");
sysytem("mode con cols=100 lines=40");
启动时切换英文输入法
keybd_event(VK_SHIFT,0,0,0);
Sleep(100);
keubd_event(VK_SHIFT,0,KEYEVENTF_KEYUP,0);
播放声音音效
#include<windows.h>
#pragma comment(lib,"winmm.lib")
//可以是相对地址,
PlaySoundA("\\start.wav",NULL,SND_FILENAME|SND_ASYNC|SND_NODEFAULT);
//结束播放
PlaySound(NULL, NULL, SND_PURGE);
设置光标
/*
0=黑色, 8=灰色,
1=蓝色, 9=淡蓝色,
2=绿色, A=淡绿色,
3=湖蓝色, B=淡浅绿色,
4=红色, C=淡红色,
5=紫色, D=淡紫色,
6=黄色, E=淡黄色,
7=白色, F=亮白色
*/
HANDLE hstd = GetStdHandle(STD_OUTPUT_HANDLE);
//设置光标位置
COORD pos = {x,y};
SetConsoleCursorPosition(hstd,pos);
//光标可见性,true为可见,false为不可见,第一个元素为光标大小
CONSOLE_CURSOR_INFO cci = { 1,FALSE };
SetConsoleCursorInfo(winhandle, cci);
//设置文本颜色
SetConsoleTextAttribute(hstd,color);
键盘事件和鼠标事件
void WriteChar(short x, short y, const char *pStr, WORD color = 1 | 8);
void OutputPos(int nx, int ny);
void KeyEventProc(KEY_EVENT_RECORD ker);
void MouseEventProc(MOUSE_EVENT_RECORD mer);
int MessageLoop();
int main()
{
MessageLoop();
getchar();
return 0;
}
//调整光标位置,输出消息
void WriteChar(short x, short y, const char * pStr, WORD color)
{
COORD pos = { x * 2,y };
HANDLE hOutStd = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleCursorPosition(hOutStd, pos);
SetConsoleTextAttribute(hOutStd,color);
printf("%s", pStr);
}
//用来输出鼠标移动信息
void OutputPos(int nx, int ny)
{
char szBuf = { 0 };
sprintf_s(szBuf, sizeof(szBuf), "x=%2d,y=%2d", nx / 2, ny);
SetConsoleTitleA(szBuf);
WriteChar(0, 0, szBuf, 0x50);
}
//用来看键盘事件
void KeyEventProc(KEY_EVENT_RECORD ker)
{
if (ker.bKeyDown)
WriteChar(0, 0, "键盘按下", 0x50);
else
WriteChar(0, 0, "键盘弹起", 0x50);
}
//用来看鼠标事件
//查看鼠标事件时,需要把控制台属性中快速编辑和插入的选项去掉
void MouseEventProc(MOUSE_EVENT_RECORD mer)
{
switch (mer.dwEventFlags)
{
case 0:
if (mer.dwButtonState == FROM_LEFT_1ST_BUTTON_PRESSED)
{
WriteChar(0, 0, "左键单击", 0x50);
}
else if (mer.dwButtonState == RIGHTMOST_BUTTON_PRESSED)
{
WriteChar(0, 0, "右键单击", 0x50);
}
break;
case DOUBLE_CLICK:
WriteChar(0, 0, "双击", 0x50);
break;
case MOUSE_MOVED:
OutputPos(mer.dwMousePosition.X, mer.dwMousePosition.Y);
break;
}
}
//事件循环查看
int MessageLoop()
{
HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
INPUT_RECORD stcRecord = { 0 };
DWORD dwRead;
SetConsoleMode(hStdin, ENABLE_WINDOW_INPUT | ENABLE_MOUSE_INPUT);
while (1)
{
ReadConsoleInput(hStdin, &stcRecord, 1, &dwRead);
if (stcRecord.EventType == KEY_EVENT)
{
KeyEventProc(stcRecord.Event.KeyEvent);
}
else if (stcRecord.EventType == MOUSE_EVENT)
{
MouseEventProc(stcRecord.Event.MouseEvent);
}
}
return 0;
}
页:
[1]