首页 > 解决方案 > 表单执行串口命令,5秒后退出

问题描述

我需要一个在执行时执行串行通信的 .exe。他们的脚本工作正常,但我需要它在不单击按钮(只需执行它)并在 5 秒后退出 .exe 的情况下使其工作。说得通?

如果单击按钮,则在我拥有并且正在工作的代码下方:

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;
using System.IO.Ports;

namespace XXXX
{
public partial class Form1 : Form
{
    public Form1()
    {
        TopMost = true;
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
    }
    private void button1_Click(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();
    }
}
}

标签: c#serial-port

解决方案


尝试将代码放入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();
    }

推荐阅读