些時候,我們需要在 Windows 平臺以管理員權限運行某個應用程序。這樣的應用程序會在右下角有一個小盾牌的圖標:
Windows 如何知道一個應用程序需要在運行時獲取管理員權限?這是通過嚮應用程序的 exe 文件中注入一個 manifest 文件來告知的。知道了這個原理,我們就可以編譯出需要管理員權限的 Qt 程序了。下面就是編譯過程。
1. 創建一個普通的 Qt 工程。
2. 在這個 Qt 工程中添加一個 XML 文件,命名爲 menifest.xml。
menifest.xml 文件內容如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 | <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> <assemblyIdentity version="1.0.0.0" processorArchitecture="X86" name="applicationname" type="win32"></assemblyIdentity> <description>Description of application</description> <!-- Identify the application security requirements. --> <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2"> <security> <requestedPrivileges> <requestedExecutionLevel level="requireAdministrator" uiAccess="false"></requestedExecutionLevel> </requestedPrivileges> </security> </trustInfo> </assembly> |
3. 在 .pro 文件中添加下面語句:
1
2
3
|
win32{
QMAKE_POST_LINK+=mt-manifest$$PWD/manifest.xml-outputresource:$$OUT_PWD/debug/$$TARGET".exe"$$escape_expand(\n\t)
}
|
在這段語句中,win32
塊表示僅在 Windows 平臺纔會運行其中的語句。這保證了我們的項目能夠跨平臺編譯。QMAKE_POST_LINK
意味着會在鏈接結束之後執行後面的語句,也就是在鏈接完成後運行:
1 | mt -manifest $$PWD/manifest.xml -outputresource:$$OUT_PWD/debug/$$TARGET".exe" $$escape_expand(\n\t) |
這是一條普通的 CMD 命令,因此需要注意的是,mt(即 mt.exe)必須在環境路徑中(mt.exe 是 VS 開發環境提供的一個工具,一般安裝過 VS 都會有這個工具)。同時還要注意,$$PWD/manifest.xml
和$$OUT_PWD/debug/$$TARGET".exe"
都是正確的路徑。爲確保路徑正確,可以在 .pro 文件中使用message()
函數輸出,例如:
1
|
message($$OUT_PWD/debug/$$TARGET".exe")
|
準備完畢之後,重新運行 qmake 再重新構建工程,就可以得到我們想要的可執行程序了:
注意,如果生成失敗,可重新嘗試運行 qmake 再次構建。還需要注意三個路徑的問題:mt.exe,$$PWD/manifest.xml 以及 $$OUT_PWD/debug/$$TARGET”.exe”。
可以直接在pro文件里加
QMAKE_LFLAGS += /MANIFESTUAC:\"level=\'requireAdministrator\' uiAccess=\'false\'\"