You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# WPF通过注册表获取游戏路径并启动进程的问题

修复注册表读写与游戏启动问题

原代码的核心问题

  • 注册表写入语法完全错误:CreateSubKey的第二个参数应为注册表权限枚举,而非直接调用SetValue,这会导致编译失败
  • 未做空值校验:读取InstallLocation时未判断子键或值是否存在,直接ToString()会触发空引用异常
  • 缺失游戏启动逻辑:完全没实现查找游戏exe并启动的需求
  • 注册表视图不一致:读取用了64位视图,写入却用默认视图,可能导致写入的键在错误的位置

修正后的完整代码

using System;
using System.Diagnostics;
using System.Windows;
using Microsoft.Win32;

namespace wpfApp
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 1. 读取Steam游戏的安装路径(64位注册表视图)
                using var localMachine = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
                using var steamUninstallKey = localMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Steam App 4000", false);
                
                if (steamUninstallKey == null)
                {
                    MessageBox.Show("未找到GMod的注册表信息");
                    return;
                }

                var installLocationObj = steamUninstallKey.GetValue("InstallLocation");
                if (installLocationObj == null || string.IsNullOrWhiteSpace(installLocationObj.ToString()))
                {
                    MessageBox.Show("注册表中未记录GMod安装路径");
                    return;
                }

                string installPath = installLocationObj.ToString();

                // 2. 写入自定义注册表路径
                using var targetKey = localMachine.CreateSubKey(@"SOFTWARE\WpfApp");
                targetKey.SetValue("NewInstallPath", installPath, RegistryValueKind.String);

                // 3. 查找并启动游戏EXE
                string gameExePath = System.IO.Path.Combine(installPath, "garrysmod.exe");
                if (!System.IO.File.Exists(gameExePath))
                {
                    MessageBox.Show($"未找到游戏文件:{gameExePath}");
                    return;
                }

                Process.Start(new ProcessStartInfo(gameExePath)
                {
                    WorkingDirectory = installPath // 设置工作目录为游戏安装路径,避免启动异常
                });
            }
            catch (Exception ex)
            {
                MessageBox.Show($"操作失败:{ex.Message}");
            }
        }
    }
}

关键修复说明

  • 安全读取注册表:先检查子键和值是否存在,避免空引用异常,同时明确使用64位视图保证读取到正确的Steam注册表项
  • 正确写入注册表:统一使用64位视图打开目标子键,调用SetValue完成写入操作,语法符合API要求
  • 完整游戏启动逻辑:拼接GMod的exe路径(garrysmod.exe),检查文件存在后用Process.Start启动,同时设置工作目录确保游戏正常加载
  • 异常捕获:包裹所有可能出错的操作,弹出错误提示避免程序崩溃

内容的提问来源于stack exchange,提问作者Miro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 07:05:23