表单执行串口命令并在5秒后退出
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了表单执行串口命令并在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
");
serialPort1.Close();
}
}
}
答案
尝试将代码放在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
");
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();
}
以上是关于表单执行串口命令并在5秒后退出的主要内容,如果未能解决你的问题,请参考以下文章