简体   繁体   English

使用 C# windows 窗体远程关闭 PC?

[英]Remote shutdown PC using C# windows form?

I'm trying to shutdown PC remotely programmatically using c# via command prompt and I already done a few search and found out this kind of codes.我正在尝试通过命令提示符使用 c# 以编程方式远程关闭 PC,我已经进行了一些搜索并找到了这种代码。

System.Diagnostics.Process.Start("shutdown", "/s");

And since it doesn't spicify any pc which to shutdown so I tried changing that codes to this codes which I think satisfy my goal.而且由于它没有说明要关闭的任何电脑,所以我尝试将该代码更改为我认为满足我的目标的代码。 But it turns out that this doesn't work.但事实证明这是行不通的。

System.Diagnostics.Process.Start("shutdown", "/s /m \\192.168.1.21 /t 5 /c 'Shutdown in 5 seconds'");

NO Exception in C# it just don't shutdown. C# 中没有异常,它只是不关闭。

I also try this but no luck.我也试过这个,但没有运气。

 System.Diagnostics.Process.Start("shutdown /s /m \\192.168.1.21 /t 5 /c 'Shutdown in 5 seconds'");

C# Exception "The system cannot find file specified". C# 异常“系统找不到指定的文件”。

EDIT:编辑:

I forgot to tell you that I alredy set up my remote computer and server the way that it will not fail to connect to each other such as turning off the firewall, configuring Local system policy and changing network and sharing center.我忘了告诉你,我已经将我的远程计算机和服务器设置为不会相互连接失败的方式,例如关闭防火墙、配置本地系统策略以及更改网络和共享中心。

in C#, \\\\ in string means \\在 C# 中,字符串中的 \\\\ 表示 \\

so the parameter interpreted as所以参数解释为

/s /m \\192.168.1.21 /t 5 /c 'Shutdown in 5 seconds' /s /m \\192.168.1.21 /t 5 /c '5 秒后关机'

you should use \\\\\\\\ to represent \\\\您应该使用 \\\\\\\\ 来表示 \\\\

or add an @ mark before the start quote mark like this或者像这样在开始引号之前添加@ 标记

System.Diagnostics.Process.Start("shutdown", @"/s /m \\\\192.168.1.21 /t 5 /c 'Shutdown in 5 seconds'"); System.Diagnostics.Process.Start("shutdown", @"/s /m \\\\192.168.1.21 /t 5 /c '5 秒后关闭'");

You can have a look at the SO post below.您可以查看下面的 SO 帖子。 It talks about rebooting a remote machine.它谈到重新启动远程机器。

WMI to reboot remote machine WMI 重启远程机器

If you look at the Win32Shutdown method如果你看一下Win32Shutdown方法

Shutdown => 1 (0x1) & Reboot => 2 (0x2)关机 => 1 (0x1) & 重启 => 2 (0x2)

So in the SO link above you will have to change所以在上面的 SO 链接中,你将不得不改变

 // Add the input parameters.
 inParams["Flags"] =  2; //Reboot

to

 // Add the input parameters.
 inParams["Flags"] =  1; //Shutdown

This should work:这应该有效:

System.Diagnostics.Process.Start("shutdown", @"-m \\192.168.1.21 -s -f -t 0");

Flags should be syntaxed like -m , not /m.标志的语法应该像 -m ,而不是 /m。

Even better is to create a "silent" shutdown (without cmd-window to show):更好的是创建一个“静默”关闭(不显示 cmd 窗口):

var shutdown = new ProcessStartInfo("shutdown", @"-m \\192.168.1.8 -s -f -t 0");
shutdown.CreateNoWindow = true;
shutdown.UseShellExecute = false;
Process.Start(shutdown);

Tested in win7, .Net framework 4.03在 win7、.Net 框架 4.03 中测试

// Remote Shutdown // 远程关机

    public bool RemoteShutdown(string userName, string password, string ip)
    {
        try
        {
            ConnectionOptions op = new ConnectionOptions();
            op.Username = userName;
            op.Password = password;
            // Make a connection to a remote computer.  
            ManagementScope scope = new ManagementScope("\\\\" + ip + "\\root\\cimv2", op);
            scope.Connect();
            //Query system for Operating System information  
            ObjectQuery oq = new ObjectQuery("SELECT * FROM Win32_OperatingSystem");
            ManagementObjectSearcher query = new ManagementObjectSearcher(scope, oq);
            ManagementObjectCollection queryCollection = query.Get();
            foreach (ManagementObject obj in queryCollection)
            {
                obj.InvokeMethod("ShutDown", null); //shutdown  
            }

            return true;
        }
        catch (Exception)
        {
            return false;
        }
    }

// Remote Reboot // 远程重启

    public bool RemoteReboot(string userName, string password, string ip)
    {
        try
        {
            ConnectionOptions op = new ConnectionOptions();
            op.Username = userName;
            op.Password = password;
            // Make a connection to a remote computer.  
            ManagementScope scope = new ManagementScope("\\\\" + ip + "\\root\\cimv2", op);
            scope.Connect();
            //Query system for Operating System information  
            ObjectQuery oq = new ObjectQuery("SELECT * FROM Win32_OperatingSystem");
            ManagementObjectSearcher query = new ManagementObjectSearcher(scope, oq);
            ManagementObjectCollection queryCollection = query.Get();
            foreach (ManagementObject obj in queryCollection)
            {
                obj.InvokeMethod("Reboot", null); //shutdown  
            }

            return true;
        }
        catch (Exception)
        {
            return false;
        }
    }

This is the code I use for shutdown / reboot remote machines:这是我用于关闭/重启远程机器的代码:

int waitSeconds = 0;
string remoteHostNameOrIp = "192.168.0.1";
ProcessStartInfo processInfo = new ProcessStartInfo();
processInfo.FileName = "shutdown.exe";
processInfo.Arguments = $@"-s -t { waitSeconds } -m \\{ remoteHostNameOrIp }";
processInfo.WindowStyle = ProcessWindowStyle.Hidden;
processInfo.CreateNoWindow = true;

var proc = Process.Start(processInfo);

// Works without WaitForExit(); 
// When using this you can check in "proc" if the shutdown was accepted by 
// the remote machine 
// 
// proc.WaitForExit();

Here is my complete solution for reboot (change -r to -s to change it to shutdown) 这是我重新启动的完整解决方案(将 -r 更改为 -s 以将其更改为关闭)

You must also enable the "Remote Registry" service on the target computer, AND you must have admin rights on the remote computer.您还必须在目标计算机上启用“远程注册表”服务,并且您必须在远程计算机上具有管理员权限。

See here for details . 有关详细信息,请参见此处

thanks for the createnowindow, i was already thinking to use it if everything works (but its unusefull if you want to see what is happening)感谢 createnowindow,如果一切正常,我已经在考虑使用它(但如果你想看看发生了什么,它就没用)

No comments without explaination about my dashes.没有对我的破折号进行解释的评论。 as long as i know, you can choose between - or /只要我知道,你可以选择 - 或 /

try it yourself :-) Start+R (run) you will see it works :)自己试试 :-) Start+R (run) 你会看到它有效:)

i think its to much work to solve it.我认为解决它需要做很多工作。

So i figgerd out that a able to use a file "FILENAME.cmd"所以我发现能够使用文件“FILENAME.cmd”

with "shutdown -s -m \\IP -t 40" in it里面有“shutdown -s -m \\IP -t 40”

The delay for reminder to close or save stuff (not nessecary)提醒关闭或保存内容的延迟(不是必需的)

the -f doesn't work for me -f 对我不起作用

but with the cmd file i can call it and let it run from my application.但是使用 cmd 文件,我可以调用它并让它从我的应用程序中运行。

So my problem is solved, i know its a little bit.... not perfect.所以我的问题解决了,我知道它有点......不完美。 but it works at least.但它至少有效。

Thanx to all for quick reply's感谢所有人的快速回复

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM