且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Windows 和控制台应用程序之间的区别

更新时间:2023-10-16 22:32:40

唯一的区别是,如果控制台应用程序不是从一个控制台启动(或者控制台在启动时被主动抑制),它总是会生成一个控制台.另一方面,Windows 应用程序不会产生控制台.它仍然可以附加到现有的控制台或使用 AllocConsole 创建一个新的控制台.

The sole difference is that a console application always spawns a console if it isn't started from one (or the console is actively suppressed on startup). A windows application, on the other hand, does not spawn a console. It can still attach to an existant console or create a new one using AllocConsole.

这使得 Windows 应用程序更适合 GUI 应用程序或后台应用程序,因为您通常不希望为这些应用程序创建终端窗口.

This makes Windows applications better suited for GUI applications or background applications because you usually don't want to have a terminal window created for those.

从技术角度来说,控制台和 Windows 可执行文件之间的唯一区别是 exe 文件的 PE 标头中的一个字节.手动切换这个字节(例如使用十六进制编辑器)转换应用程序类型.这是一个发布良好的 hack,用于在 VB6 中创建控制台应用程序(未明确支持此类应用程序).

On a more technical note, the only difference between a Console and a Windows executable is one byte in the PE header of the exe file. Toggling this byte manually (e.g. using a hex editor) converts the application type. This is a well-published hack that is used to create console applications in VB6 (where this type of application was not explicitly supported).

要确定和更改应用程序的子系统类型,您需要读取部分 PE 标头.但是,子系统数据的地址不是固定的,因为它是可选文件头的一部分,其位置由存储在 DOS 文件头(在成员 e_lfanew 中)中的地址确定.该地址实际上指向 _IMAGE_NT_HEADERS 记录,而该记录又包含 IMAGE_OPTIONAL_HEADER32 结构.它有一个名为 Subsystemint161) 成员.该成员的值为 Windows 应用程序的 2 和控制台应用程序的 3.存在其他子系统(特别是 POSIX 和内核).我写了一个小的 VB6 应用程序来改变一个应用程序的子系统,可以从 ActiveVB 作为源代码.

To determine and change the subsystem type of an application, you need to read parts of the PE header. The address of the subsystem data is not fixed though, because it's part of the optional file header whose position is determined by an address stored in the DOS file header (in the member e_lfanew). This address actually points to the _IMAGE_NT_HEADERS record which, in turn, includes the IMAGE_OPTIONAL_HEADER32 structure. This has an int161) member called Subsystem. The member's value is 2 for a Windows application and 3 for a console application. Other subsystems exist (in particular, POSIX and kernel). I've written a small VB6 application to change the subsystem of an application, which can be downloaded from ActiveVB as source code.

PE 格式没有很好的文档记录,但本文档可以作为介绍:深入了解 PE:Win32 可移植可执行文件格式之旅.

The PE format isn't very well documented but this document may serve as an introduction: Peering Inside the PE: A Tour of the Win32 Portable Executable File Format.

1) 这与我声称只有一个字节不同的说法并不矛盾:该成员的最高有效字节始终为 0.只有最低有效字节发生变化.

1) This doesn't really contradict my claim that only one byte differs: the most significant byte of this member is always 0. Only the least significant byte changes.