我的应用程序是从Visual Studio内部运行还是执行EXE文件

问题描述 投票:-7回答:2

由于我经常在Microsoft Visual Studio 2017内部/外部测试我的二进制文件,因此我想控制C / C ++控制台项目中代码的行为。

  • 一个代码,用于在发布模式下从Visual Studio中运行.exe。
  • 另一个当我从资源管理器中单击我的.exe时。

我应该使用什么标志或函数来了解我的.exe是否是从Visual Studio内部启动的。

我想要实现的是:

#if !_RELEASE
    system("pause"); // prevents auto shutdown of my .exe in Explorer
                     // double click
#endif

其中_RELEASE是在Studio启动时触发代码的某种特性,但在资源管理器双击中不可见。

c++ visual-studio winapi
2个回答
1
投票

我应该使用什么标志或函数来了解我的进程是否是从Visual Studio内部启动的。

  1. 您不应该从程序代码中执行此类行为控制。这是糟糕的设计,并使您的程序代码混乱,应该留在调用者身上。 我建议你是否需要不同的程序行为(例如在后台运行或使用可见的GUI),这应该用例如配置文件或命令行参数。 您可以同时执行此操作,Visual Studio设置以指定cmd行参数,或使用其他配置文件,甚至两者的组合。
  2. 因为你似乎坚持要求解决你的想法如何以最好的方式摆弄这个: 您可以使用WINAPI函数迭代父进程ID,并检查其中一个是否与“Visual Studio”模块匹配。 这是一个与技术相关的问答: How can I reliably check whether one Windows process is the parent of another in C++?

-3
投票

它不完全是解决方案,但是:

Raymond Chen(微软winapi大师*)与我面临的问题最为接近,帮助我检测我运行控制台会话的模式或环境。

How can I tell whether my console program was launched from Explorer or from a command prompt?

printf("this process = %d\n", GetCurrentProcessId());
DWORD count = GetConsoleProcessList(nullptr, 0);
if (count == 1) {
    printf("I'm the last one!\n");
    Sleep(2000);
}
else {
    printf("I'm not the last one! %d\n", count);
}
© www.soinside.com 2019 - 2024. All rights reserved.