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

C# WinForm远程关机功能失效问题求助

C# WinForm远程关机功能失效问题求助

嗨,我看了你的代码和问题描述,远程关机没生效主要是命令参数写错了,还有代码里的一些小冗余,咱们一步步来搞定它:

先说说你代码里的核心问题

  1. 关机命令参数完全错了:你写的/3DI根本不是shutdown命令的合法参数,远程指定计算机应该用/m \\{ipAddress}才对
  2. 重复启动CMD进程:你先直接调用了Process.Start("cmd.exe", ...),后面又用ProcessStartInfo再启动一次,这不仅多余,还会导致你没法捕获第一次启动进程的错误信息
  3. 没强制关闭程序:最好加上/f参数,强制关闭目标电脑上的所有程序,避免因为有未保存的文件导致关机失败

修正后的完整代码

public partial class Form1 : Form
{
    private void PC_OFF_BTN_Click(object sender, EventArgs e)
    {
        String ipAddress = textBox2.Text.Trim();
        if (string.IsNullOrWhiteSpace(ipAddress))
        {
            MessageBox.Show("유효한 IP 주소를 입력하세요");
            return;
        }
        if (MessageBox.Show("종료?", "YesOrNo", MessageBoxButtons.YesNo) == DialogResult.Yes)
        {
            MessageBox.Show("Yes");
            ShutdownRemotePC(ipAddress);
        }
        else
        {
            MessageBox.Show("No");
        }
    }
 
    private void ShutdownRemotePC(string ipAddress)
    {
        try
        {
            // 修正后的命令:/c 让CMD执行完命令就退出,/m 指定远程IP,/f 强制关闭程序
            string shutdownCommand = $"/c shutdown /s /m \\\\{ipAddress} /t 0 /f";
            
            ProcessStartInfo processInfo = new ProcessStartInfo
            {
                FileName = "cmd.exe",
                Arguments = shutdownCommand,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                UseShellExecute = false,
                CreateNoWindow = true
            };

            using (Process process = Process.Start(processInfo))
            {
                // 读取输出和错误信息,方便排查问题
                string output = process.StandardOutput.ReadToEnd();
                string error = process.StandardError.ReadToEnd();
                process.WaitForExit();

                if (process.ExitCode == 0)
                {
                    MessageBox.Show("전송 완료.");
                }
                else
                {
                    // 把错误信息弹出来,方便你调试哪里出问题
                    MessageBox.Show($"원격 종료 오류 상세: {error}\n출력 로그: {output}");
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("원격 종료 오류: " + ex.Message);
        }
    }
}

另外还要检查这些系统配置(非常重要!)

就算代码对了,目标电脑的设置不对也会失败:

  • 目标电脑要开启Remote Registry和Windows Management Instrumentation服务(可以在服务管理器里找)
  • 你用来运行程序的账号,必须是目标电脑的管理员组成员
  • 目标电脑的防火墙要允许远程关机请求(可以先临时关防火墙测试,确认没问题再配置规则)
  • 如果是工作组环境,目标电脑需要开启文件和打印机共享(远程关机依赖这个协议)

备注:内容来源于stack exchange,提问作者HOON

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.15 09:15:31