表格执行串口命令并在5秒后退出

时间:2018-09-05 07:44:36

标签: c# serial-port

我需要一个.exe,它在执行时会执行串行通信。他们的脚本工作正常,但是我需要它来使它工作而无需单击按钮(仅通过执行它),并在5秒后退出.exe。有道理吗?

在我拥有的代码下面,如果我单击该按钮,它将起作用:

{{1}}

1 个答案:

答案 0 :(得分:0)

尝试将代码放入Form.Shown事件中,以使该命令仅在加载表单时触发。使用System.Threading.Thread.Sleep,您可以让您的应用程序等待一段时间。

    private void Form1_Shown(Object sender, EventArgs e)
    {
        serialPort1.PortName = "COM2";
        serialPort1.BaudRate = 9600;
        serialPort1.Parity = Parity.None;
        serialPort1.DataBits = 8;
        serialPort1.StopBits = StopBits.One;
        serialPort1.Handshake = Handshake.None;
        serialPort1.Open();
        serialPort1.Write("XXXX\r");
        serialPort1.Close();
        //will stop the executing thread for given amount of time. However if you want remain responsive (UI doesn't freeze) you might consider timers.
        System.Threading.Thread.Sleep(5000);
        //close the application
        Application.Exit();
    }