簡體   English   中英

打開命令提示符並從Windows窗體應用程序執行命令

[英]open Command Prompt and execute commands from Windows Form Application

我正在使用套接字,服務器是Windows窗體應用程序,客戶端是android應用程序。 我正在通過客戶端發送命令命令,並想在服務器上執行這些命令,我​​想打開命令提示符並執行從客戶端收到的命令,並在服務器端的textBox中顯示響應,但是當我運行我的應用程序時,Windows窗體應用程序再次打開將打開命令提示符,並執行命令。

這是我的功能,處理從android客戶端收到的請求

   private void HandleMsg(String s)
    {
      if (s == "SS")
        {
            STW.WriteLine("SendingImage");
            SendScreenToClient();
        }
        else
        {
            try
            {
                Process myprocess = new Process();
                System.Diagnostics.ProcessStartInfo StartInfo = new System.Diagnostics.ProcessStartInfo();
                StartInfo.FileName = "cmd"; // starts cmd window
                StartInfo.RedirectStandardInput = true;
                StartInfo.RedirectStandardOutput = true;
                StartInfo.UseShellExecute = false; // required to redirect
                StartInfo.CreateNoWindow = true; // <---- creates no window, obviously
                myprocess.StartInfo = StartInfo;
                myprocess.Start();
                System.IO.StreamReader SR = myprocess.StandardOutput;
                System.IO.StreamWriter SW = myprocess.StandardInput;
                SW.WriteLine(s); // the command you wish to run.....
                SW.WriteLine("exit"); // exits command prompt window
                textBox3.Text = SR.ReadToEnd(); // returns results of the command window
                SW.Close();
                SR.Close();
            }
            catch(Exception E) { MessageBox.Show(E.ToString());}
    }
    }

您需要檢出Windows Management Instrumentation(WMI),尤其是System.Management接口。 請參閱官方文檔中的示例。

然后,您可以使用類似:

var wProcess = new ManagementClass(wScope, new ManagementPath("Win32_Process"), new ObjectGetOptions());
wProcess.InvokeMethod("Create", new[] { "cmd.exe" });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM