问题描述
我正在尝试使用winapi函数打个招呼世界。这是一种工作方式,但我想以正确的方式进行操作。
I'm trying to do hello world with winapi functions. It's kind of working but I would love to have it done the proper way.
所以我得到了这样的代码:
So i got code like this:
int main(){
HANDLE std_out;
int i;
char *error_msg;
std_out = GetStdHandle(STD_OUTPUT_HANDLE);
if(std_out == INVALID_HANDLE_VALUE){
MessageBox(NULL,"stdout not available","Error",MB_OK);
return 1;
}
AttachConsole(ATTACH_PARENT_PROCESS);
if(!WriteConsoleA(std_out,"hhh\n",4,&i,NULL)){
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,NULL,GetLastError(),0,&error_msg,4,NULL);
MessageBox(NULL,error_msg,"Error",MB_OK);
}
return 42;
}
我也做了一些实验,所以我连接了/ entry:main / subsystem:windows
Also I'm a little bit experimenting so I link with /entry:main /subsystem:windows
然后输出如下:
%PATH_TO_WORKING_DIR%>hhh(CRLF)
然后等待,直到按回车键,然后程序终止,您可能同意,这是一个非常混乱的 hello world。非常欢迎任何有关如何消除该PWD和必须按回车的想法,以供阅读。
then it waits until I press RETURN and then the program terminates, which as you probably agree is very crapy "hello world". Any ideas how to get rid of that PWD and necessity to press return are very welcomed, thx for reading.
推荐答案
您强制充当控制台应用程序的GUI应用程序。我猜cmd.exe(或任何父级)变得困惑,因为你们俩都认为自己是自己的标准输出。
This is a GUI application that you force to act like a console application. I'm guessing cmd.exe (or whatever the parent is) is getting confused as you both think you "own" stdout.
与/ SUBSYSTEM:CONSOLE和问题应该消失(然后您就不需要/ ENTRY或对AttachConsole的调用)
Link with /SUBSYSTEM:CONSOLE and the problems should go away (and then you don't need /ENTRY or the call to AttachConsole)
如果您确实想要GUI /控制台混合,则需要调用AllocConsole没有控制台时(从资源管理器等启动)
If you actually want a GUI/Console hybrid, you need to call AllocConsole when there is no console (Started from Explorer etc)
这篇关于使用WinAPI WriteConsole的控制台输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!