C++ (VC2010) 帮助将控制台应用程序转换为隐藏的 Windows 应用程序?

C++ (VC2010) Help converting console app to hidden Windows app?

我已经阅读了十几页,解释了如何将 Win32 控制台应用程序转换为 Windows 应用程序,该应用程序 运行 无需短暂打开和关闭控制台 window,但我太新手了,无法让它发挥作用。

例如,在 VC2010 中,我在此处描述的项目属性中进行了两项更改:

convert a console app to a windows app

并将 Main 更改为 WinMain,但当然会收到来自编译器的错误消息。

按照其他页面,我还尝试创建控制台应用程序,然后在 Win32 应用程序向导中将应用程序类型更改为 Windows 应用程序,但我不知道下一步该怎么做.我试过将 int Main 更改为 int CALLBACK WinMain,但这当然也不起作用。

有没有人可以帮助初学者?这是我认为是我的代码编辑的相关部分:完整的代码,对于任何想知道这是干什么的人,在这里:

https://www.dropbox.com/s/1h8x1k2zv0lc5d1/vPasteCPlus.txt?dl=0

#include <stdafx.h>
#include <windows.h>
#include <iostream>
#include <fstream>
#include <codecvt> // for wstring_convert
#include <locale>  // for codecvt_byname
using namespace std;

// helper to get path to this application
string ExePath() {
char buffer[MAX_PATH];
GetModuleFileNameA( NULL, buffer, MAX_PATH );
string::size_type pos = string( buffer ).find_last_of( "\/" );
return string( buffer ).substr( 0, pos);
}

int main(int argc, char* argv[])
{
    // get the command-line argument if any, and do various things
} 

再次为这个初学者问题道歉。我使用 C++ 的唯一经验是编写控制台应用程序,如有任何建议,我们将不胜感激。

如果这是一个 Visual Studio 项目(正如 <stdafx.h> 强烈表明的那样),那么:

  • 在链接器设置中将子系统设置为 Windows。
  • 将入口点设置为 mainCRTStartup(调用标准 main)。

但是你确定要这个吗?

听起来你想要的是一个Windows服务?

好的,您已经打开了 Visual Studio。你有 Solution Explorer(如果没有,View -> Solution Explorer)。

首先,要制作 Windows 应用程序,您应该将入口点从 main()(C++ 标准)更改为 Windows-specific WinMain()。请参阅 more detailed description 的 msdn。因此,您正在将 main() 更改为下一个(从文档中复制粘贴):

int CALLBACK WinMain(
  _In_ HINSTANCE hInstance,
  _In_ HINSTANCE hPrevInstance,
  _In_ LPSTR     lpCmdLine,
  _In_ int       nCmdShow)
{
    return 0;
}

当然,你应该包括<Windows.h>,因为Windows提供了它自己的API用于与系统一起工作(例如LPSTR类型)。简而言之,您完成了编译器编译程序所需的所有工作。您可以构建您的解决方案 (Build -> Build Solution)...这将导致 linker 错误:

error LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup

再次,编译器做了你想要的一切并将你的源文件编译成 .obj,但是,因为你的项目是为控制台应用程序配置的,linker 需要控制台应用程序的标准入口点 - main 并且在我们的例子中找不到(解析)它,因为我们将 main 更改为 WinMain。为了让链接器开心,你应该告诉它:

  • 右键单击里面的项目Solution Explorer
  • 然后点击Properties
  • 转到 Configuration Properties -> Linker -> System 并将 SubSystem 设置为 Windows

尝试再次构建您的应用程序,瞧 - 您已经没有链接器错误,因为您的链接器现在知道它需要生成 Windows 应用程序并找到 Windows 入口点:WinMain() !

关于这个:

// get the command-line argument if any, and do various things

你应该使用 WinMain()lpCmdLine 参数。但是要小心,如果你 运行 你的程序(例如 so.exe)像这样:

so.exe arg1 arg2

lpCmdLinearg1 arg2 字符串。你可以做很多事情来获得 arg1arg2 asn 像 main() argv 中的数组(使用 argc),但你可以探索:

和相关内容(例如 Windows 上的 wchar_t)