問題描述
您將如何編寫無需打開窗口或控制臺即可運行的 C/C++ 應用程序?
How would you program a C/C++ application that could run without opening a window or console?
推薦答案
當您編寫 WinMain 程序時,您會自動將/SUBSYSTEM 選項設置為編譯器中的窗口.(假設您使用 Visual Studio).對于任何其他編譯器,可能存在類似的選項,但標志名稱可能不同.
When you write a WinMain program, you automatically get the /SUBSYSTEM option to be windows in the compiler. (Assuming you use Visual Studio). For any other compiler a similar option might be present but the flag name might be different.
這會導致編譯器以可執行文件格式(PE 格式) 將可執行文件標記為 Windows 可執行文件.
This causes the compiler to create an entry in the executable file format (PE format) that marks the executable as a windows executable.
一旦此信息出現在可執行文件中,啟動程序的系統加載程序會將您的二進制文件視為 Windows 可執行文件而不是控制臺程序,因此它不會導致控制臺窗口在運行時自動打開.
Once this information is present in the executable, the system loader that starts the program will treat your binary as a windows executable and not a console program and therefore it does not cause console windows to automatically open when it runs.
但是如果不需要,Windows 程序不需要創建任何窗口,就像您在任務欄中看到的所有那些程序和服務一樣,但沒有看到任何對應的窗口.如果您創建了一個窗口但選擇不顯示它,也會發生這種情況.
But a windows program need not create any windows if it need not want to, much like all those programs and services that you see running in the taskbar, but do not see any corresponding windows for them. This can also happen if you create a window but opt not to show it.
你需要做的就是實現這一切,
All you need to do, to achieve all this is,
#include <Windows.h>
int WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int cmdShow)
{
/* do your stuff here. If you return from this function the program ends */
}
您需要 WinMain 本身的原因是,一旦您將子系統標記為 Windows,鏈接器就會假定您的入口點函數(在程序加載和 C Run TIme 庫初始化后調用)將是 WinMain 而不是 main.如果您沒有在此類程序中提供 WinMain,您將在鏈接過程中收到未解決的符號錯誤.
The reason you require a WinMain itself is that once you mark the subsystem as Windows, the linker assumes that your entry point function (which is called after the program loads and the C Run TIme library initializes) will be WinMain and not main. If you do not provide a WinMain in such a program you will get an un-resolved symbol error during the linking process.
這篇關于創建沒有窗口的應用程序的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!