我需要一些Console function 函数,有很多。
https://docs.microsoft.com/en-us/windows/console/console-functions
int APIENTRY _tWinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow){
HANDLE console=nullptr;
if (AllocConsole()) {
console = GetStdHandle(STD_OUTPUT_HANDLE);
}
else
return 0;
BOOL MsgResult=MessageBox(nullptr,nullptr,nullptr,MB_OKCANCEL|MB_DEFBUTTON2);
switch (MsgResult)
{
case IDOK: {
//do something
TCHAR message[] = TEXT("you clicked ok button\n");
WriteConsole(console, message, _countof(message), nullptr, nullptr);
break;
}
case IDCANCEL: {
TCHAR message[] = TEXT("you clicked cancel button\n");
WriteConsole(console, message, _countof(message), nullptr, nullptr);
break;
//do something
break;
}
default:
break;
}
TCHAR outMessage[] = TEXT("enter any key to end \n");
WriteConsole(console, outMessage, _countof(outMessage), nullptr, nullptr);
CloseHandle(console);
console = GetStdHandle(STD_INPUT_HANDLE);
TCHAR inputMessage[1];
DWORD count;
ReadConsole(console, inputMessage, _countof(inputMessage), &count, nullptr);
CloseHandle(console);
// You can also use the following function to complete
// system("pause");
return 0;
}
当然我们还可以使用重定向
#include<Windows.h>
#include<process.h>
#include<tchar.h>
#include<iostream>
long g_resouse = FALSE;
void thread1(void *) {
while (InterlockedExchange(&g_resouse, TRUE) == TRUE)
Sleep(0);
//访问资源
InterlockedExchange(&g_resouse, false);
}
void thread2(void *) {
while (InterlockedExchange(&g_resouse, TRUE) == TRUE)
Sleep(0);
//访问资源
InterlockedExchange(&g_resouse, false);
}
void fun() {
}
int APIENTRY _tWinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow){
FILE *outFile;
FILE *inFile;
if (AllocConsole()) {
errno_t error1;
errno_t error2;
error1=freopen_s(&outFile,"CONOUT$", "w",stdout);
error2=freopen_s(&inFile, "CONIN$", "r", stdin);
if (error1==0&&error2==0) {
BOOL MsgResult = MessageBox(nullptr, nullptr, nullptr, MB_OKCANCEL | MB_DEFBUTTON2);
switch (MsgResult)
{
case IDOK: {
//do something
std::wcout << TEXT("you clicked ok button") << std::endl;
break;
}
case IDCANCEL: {
std::wcout << TEXT("you clicked cancel button") << std::endl;
break;
//do something
break;
}
default:
break;
}
}
std::wcout << TEXT("entry any key to end") << std::endl;
std::wcin.get();
//system("pause");
fclose(outFile);
fclose(inFile);
}
return 0;
}
因为freopen再vs中提示不安全,就看看了看安全的freopen_s。此函数重定向设备并保存再第一个参数中。函数返回值返回0表示一切ok。对于CONIN$,和CONOUT$;只是windows 中保留的的两个路径名,它们用来做控制台的输入(键盘)缓冲区和活动的控制台屏幕输出缓冲区。在使用 GetStdHandle() 时,它的参数选项分别为:STD_INPUT_HANDLE,STD_OUTPUT_HANDLE 和 STD_ERROR_HANDLE。
- STD_INPUT_HANDLE 为标准输入设备,初始时表示控制台输入缓冲区,即 CONIN$ 。
- STD_OUTPUT_HANDLE 为标准输出设备,初始时表示活动的控制台屏幕输出缓冲区,即 CONOUT$ 。
- STD_ERROR_HANDLE 为标准错误设备,初始时表示活动的控制台屏幕输出缓冲区,也为 CONOUT$ 。
【参考】
http://blog.csdn.net/huiyouyongdeyu2011/article/details/6556168