首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 呼叫控制面板小工具:Process.Start 實作指南

     編輯:關於C語言

原理

控制面板項目本質為 .cpl 檔案,位於 System32 目錄。C# 可透過 Process.Start 直接啟動。

常見 CPL 檔案對照表

控制面板項目CPL 檔案
Internet 選項inetcpl.cpl
ODBC 資料來源odbccp32.cpl
電話與調變解調器telephon.cpl
電源選項powercfg.cpl
輔助功能access.cpl
地區與語言intl.cpl
日期與時間timedate.cpl
聲音與音訊mmsys.cpl
滑鼠main.cpl
新增/移除程式appwiz.cpl
新增硬體hdwwiz.cpl
網路連線ncpa.cpl
系統sysdm.cpl
顯示desk.cpl
使用者帳戶nusrmgr.cpl
遊戲控制器joy.cpl
語音sapi.cpl

基本呼叫方式

using System.Diagnostics;
using System.ComponentModel;

try
{
    Process.Start("inetcpl.cpl"); // 直接啟動 Internet 選項
}
catch (Win32Exception ex)
{
    MessageBox.Show($"出錯原因:{ex.Message}", "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

進階用法:ProcessStartInfo

ProcessStartInfo info = new ProcessStartInfo();
info.FileName = "inetcpl.cpl";
info.UseShellExecute = true; // 預設 true,使用 Shell 執行

try
{
    Process.Start(info);
}
catch (Win32Exception ex)
{
    // 錯誤處理
}

完整 WinForms 範例

using System;
using System.Diagnostics;
using System.Windows.Forms;

namespace CsharpCallCPL
{
    public class Form1 : Form
    {
        private Button btnCall;
        private Label lblTitle;

        public Form1()
        {
            InitializeComponent();
        }

        private void InitializeComponent()
        {
            this.lblTitle = new Label { Text = "C# 呼叫控制面板範例", Font = new Font("微軟正黑體", 14, FontStyle.Bold), AutoSize = true, Location = new Point(40, 16) };
            this.btnCall = new Button { Text = "呼叫 Internet 選項", Location = new Point(192, 72) };
            this.btnCall.Click += BtnCall_Click;

            this.ClientSize = new Size(296, 125);
            this.Controls.AddRange(new Control[] { lblTitle, btnCall });
            this.Text = "CPL 呼叫示範";
        }

        private void BtnCall_Click(object sender, EventArgs e)
        {
            try
            {
                Process.Start("inetcpl.cpl");
            }
            catch (Win32Exception ex)
            {
                MessageBox.Show($"出錯原因:{ex.Message}", "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        [STAThread]
        static void Main()
        {
            Application.Run(new Form1());
        }
    }
}

注意事項

  • 檔名必須完整(含 .cpl 副檔名),否則會擲回 Win32Exception。
  • 適用於 Windows 所有版本,路徑若在系統 PATH 中可直接用檔名。
  • 同樣原理可啟動任何可執行檔、文件或 URL。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved