1. 程式人生 > >win32程式中呼叫控制檯程式

win32程式中呼叫控制檯程式

#include <Windows.h>
#include <cstdio>
#define ErrorShow(Msg) MessageBox(NULL,Msg,L"ErrorShow",MB_OK)
void OnKeyProc(KEY_EVENT_RECORD k,HANDLE h)
{


WriteConsole(h, L"KeyEvent:", lstrlen(L"KeyEvent:"), NULL, NULL);
if (k.bKeyDown)
WriteConsole(h, L"KeyDown\n", lstrlen(L"KeyDown\n"), NULL, NULL);
else
WriteConsole(h, L"KeyUp\n", lstrlen(L"KeyUp\n"), NULL, NULL);
if (k.uChar.AsciiChar == 'q' || k.uChar.UnicodeChar == 'q')
ExitProcess(0);
}


void OnBufferProc(WINDOW_BUFFER_SIZE_RECORD w, HANDLE h)
{
TCHAR t[256];
wsprintf(t, L"改變之後的大小是:X=%d,Y=%d\n", w.dwSize.X, w.dwSize.Y);
WriteConsole(h, t, lstrlen(t), NULL, NULL);
}
void OnMouseProc(MOUSE_EVENT_RECORD m, HANDLE h)
{
switch (m.dwEventFlags)
{
case 0:
if (m.dwButtonState == FROM_LEFT_1ST_BUTTON_PRESSED)
WriteConsole(h, L"滑鼠左鍵被單擊\n", lstrlen(L"滑鼠左鍵被單擊\n"), NULL, NULL);
else if (m.dwButtonState== RIGHTMOST_BUTTON_PRESSED)
WriteConsole(h, L"滑鼠右鍵被單擊\n", lstrlen(L"滑鼠右鍵被單擊\n"), NULL, NULL);
break;
case DOUBLE_CLICK:
WriteConsole(h, L"雙擊\n", lstrlen(L"雙擊\n"), NULL, NULL);
break;
case MOUSE_HWHEELED:
WriteConsole(h, L"滑鼠橫向滾動\n", lstrlen(L"滑鼠橫向滾動\n"), NULL, NULL);
break;
case MOUSE_WHEELED:
WriteConsole(h, L"滑鼠縱向滾動\n", lstrlen(L"滑鼠縱向滾動\n"), NULL, NULL);
break;
case MOUSE_MOVED:
WriteConsole(h, L"滑鼠移動\n", lstrlen(L"滑鼠移動\n"), NULL, NULL);
break;

}
}
int WINAPI WinMain(
HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR CmdLine,
int nCmdShow
)
{
TCHAR BUFFER[128];
AllocConsole();
int count = 0;
SetConsoleTitle(L"聯絡");
DWORD cNumRead, fdwMode, i;
INPUT_RECORD irInBuf;
HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
if (hStdin == INVALID_HANDLE_VALUE)
{
ErrorShow(L"GetStdHandle(STD_INPUT_HANDLE) Error!");
goto Exit;
}
HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
if (hStdout == INVALID_HANDLE_VALUE)
{
ErrorShow(L"GetStdHandle(STD_OUTPUT_HANDLE) Error!");
goto Exit;
}
if (!GetConsoleMode(hStdin, &fdwMode))
{
ErrorShow(L"GetConsoleMode Error!");
goto Exit;
}
fdwMode |= ENABLE_WINDOW_INPUT | ENABLE_MOUSE_INPUT;
if (!SetConsoleMode(hStdin, fdwMode))
{
ErrorShow(L"SetCosoleMode Error!");
goto Exit;
}
//SetCurrentConsoleFontEx()


while (1)
{
if (!ReadConsoleInput(hStdin, &irInBuf, 1, &cNumRead))
{
ErrorShow(L"ReadConsoleInput error!");
goto Exit;
}
for (i = 0; i < cNumRead; i++)
{
switch (irInBuf.EventType)
{
case KEY_EVENT:      // keyboard input
OnKeyProc(irInBuf.Event.KeyEvent,hStdout);
break;
case MOUSE_EVENT:  // mouse input
OnMouseProc(irInBuf.Event.MouseEvent, hStdout);
break;
case   WINDOW_BUFFER_SIZE_EVENT: // Resizing BUFFER
OnBufferProc(irInBuf.Event.WindowBufferSizeEvent, hStdout);
break;
case FOCUS_EVENT:
//ErrorShow(L"FOCUS");
break;
case MENU_EVENT:
ErrorShow(L"MENU");
break;
default:
break;
}
}




}
//WriteConsole(hStdout, L"HelloWorld\n", lstrlen(L"HelloWorld\n"), NULL, NULL);








Exit:
system("pause");
FreeConsole();
return 0;
}