首页 > 解决方案 > 在 WinForm 中单击按钮时在远程 PC 上启动应用程序

问题描述

我正在尝试创建一个简单的 winform 来在远程机器上运行 Life is Feudal 服务器可执行文件。在服务器上用cmd启动服务器的命令是"C:\Program Files (x86)\Steam\life is feudal\ddctd_cm_yo_server.exe" WorldDS 1

现在,我正在尝试为它制作一个简单的开始/停止按钮。我以后可以弄清楚如何停止它,我只想尝试让“开始”部分工作。我不太确定从哪里开始编写代码。我现在所拥有的按钮是:'''

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace LifeIsFeudalServerManager
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Serverstatus_Click(object sender, EventArgs e)
        {

        }
        bool servcrtl = true;
        private void ServerControl_Click(object sender, EventArgs e)
        {
            if (servcrtl == true)
            {
                servcrtl = false;
                ServerControl.Text = "Stop";


            }
            else
            {
                servcrtl = true;
                ServerControl.Text = "Start";


            }
        }

    }
}

''' 我想添加一个单击事件,当按钮显示“开始”时,该事件会在第一次单击时使用“WorldDS1”参数启动可执行文件。然后,我想添加一个单击事件,当按钮显示“停止”时,该事件会在第二次单击时关闭进程。我刚开始使用 c# 并使用 Visual Studios,所以越简单越好,任何帮助将不胜感激。

标签: c#visual-studio-2017remote-serverbuttonclick

解决方案


如果程序安装在您的 PC 上并且您想要启动它,您可以执行类似的操作。首先,您必须知道可执行文件的位置和文件名。

//Pass your command string
private List<string> ExecuteCommand(string Command)
        {
            string cmdString = "C:\Program Files (x86)\Steam\life is feudal\ddctd_cm_yo_server.exe"

            List<string> CommandLineResponse = new List<string>();
            Process cmd = new Process();
            cmd.StartInfo.FileName = "cmd.exe";//the process to execute
            cmd.StartInfo.RedirectStandardInput = true;//this is set to be able to pass in string arguments to command-line
            cmd.StartInfo.RedirectStandardOutput = true;//this is set to true to get the response at the command-line
            cmd.StartInfo.CreateNoWindow = true;//do not show a command line window
            cmd.StartInfo.UseShellExecute = false;
            cmd.Start();//start the process

            cmd.StandardInput.WriteLine(cmdString);
            cmd.StandardInput.Flush();
            cmd.StandardInput.Close();
            while (!(cmd.StandardOutput.EndOfStream))
            {
                CommandLineResponse.Add(cmd.StandardOutput.ReadLine());
            }
            return CommandLineResponse;
        }

推荐阅读