问题描述
我必须创建一个需要某些参数的控制台应用程序.如果它们丢失或错误,我会打印出错误消息.
I have to create a console application which needs certain parameters. If they are missing or wrong I print out an error message.
现在的问题:如果有人通过双击从资源管理器启动程序,控制台窗口会立即消失.(但该应用程序在资源管理器中并非完全没用,您可以将文件拖到它上面就可以了)
Now the problem: If someone starts the program from the explorer by double-clicking the console window disappears immediately. (But the application is not entirely useless from the explorer, you could drag files onto it and it would work)
我可以总是等待按键,但如果用户确实从命令行启动它,我不希望这样.
I could always wait for a keypress, but I don't want that if the user did start it from the command line.
有什么方法可以区分这些情况吗?
Is there some way to distinguish between these situations?
推荐答案
参见 http://support.microsoft.com/kb/99115,信息:防止控制台窗口消失".
See http://support.microsoft.com/kb/99115, "INFO: Preventing the Console Window from Disappearing".
想法是使用GetConsoleScreenBufferInfo 来确定光标没有从最初的0,0 位置移动.
The idea is to use GetConsoleScreenBufferInfo to determine that the cursor has not moved from the initial 0,0 position.
来自@tomlogic 的代码示例,基于参考的知识库文章:
Code sample from @tomlogic, based on the referenced Knowledge Base article:
// call in main() before printing to stdout
// returns TRUE if program is in its own console (cursor at 0,0) or
// FALSE if it was launched from an existing console.
// See http://support.microsoft.com/kb/99115
#include <stdio.h>
#include <windows.h>
int separate_console( void)
{
CONSOLE_SCREEN_BUFFER_INFO csbi;
if (!GetConsoleScreenBufferInfo( GetStdHandle( STD_OUTPUT_HANDLE), &csbi))
{
printf( "GetConsoleScreenBufferInfo failed: %lu
", GetLastError());
return FALSE;
}
// if cursor position is (0,0) then we were launched in a separate console
return ((!csbi.dwCursorPosition.X) && (!csbi.dwCursorPosition.Y));
}
这篇关于Win32 控制台应用程序是否可以检测它是否已从资源管理器运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!