EKsumic's Blog

let today = new Beginning();

Click the left button to use the catalog.

OR

VS2022如何設定WinForm程式強制以管理員身分執行?

1. 手動新增 app.manifest 文件

右鍵點選 專案名稱(在「解決方案資源管理器」中)。

選擇 “Add” -> “New Item…”。

在「新增項目」對話方塊中,選擇 “XML 檔案”(XML File)。

將新檔案命名為 app.manifest,然後點擊「新增」。

 

2. 編輯 app.manifest 文件

在剛剛建立的 app.manifest 檔案中,加入以下內容:

<?xml version="1.0" encoding="utf-8"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
    <security>
      <requestedPrivileges>
        <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
      </requestedPrivileges>
    </security>
  </trustInfo>
  <dependency>
    <dependentAssembly>
      <assemblyIdentity type="win32" name="Microsoft.Windows.Common-Controls" version="6.0.0.0" processorArchitecture="*" publicKeyToken="6595b64144ccf1df" language="*" />
    </dependentAssembly>
  </dependency>
</assembly>

 

3. 手動編輯 .csproj 文件

右鍵點選 專案名稱,然後選擇 “Unload Project”。

右鍵點選專案名稱(現在變成不可用狀態),選擇 “Edit [YourProjectName].csproj”。

在 .csproj 檔案中,找到 <PropertyGroup> 節點。在這個節點內,加入以下元素:

<ApplicationManifest>app.manifest</ApplicationManifest>

 

例如:

<PropertyGroup>
  <OutputType>WinExe</OutputType>
  <TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
  <ApplicationManifest>app.manifest</ApplicationManifest>
</PropertyGroup>

儲存 .csproj 文件,然後右鍵點擊項目,選擇 “Reload Project” 來重新載入項目。

 

4. 編譯和運行

完成以上步驟後,編譯您的專案。當使用者啟動您的應用程式時,系統將彈出 UAC 提示,要求以管理員權限執行應用程式。

 

總結

透過手動新增 app.manifest 檔案並在 .csproj 檔案中引用它,您的 WinForms 應用程式將在啟動時請求管理員權限。這是確保程式可以執行需要高級權限的操作(如修改註冊表)的有效方法。

This article was last edited at 2024-08-27 14:56:12

Today's comments have reached the limit. If you want to comment, please wait until tomorrow (UTC-Time).

There is 07h22m57s left until you can comment.