c# - 表单执行串口命令,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();
}
}
}
解决方案
尝试将代码放入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();
}
推荐阅读
- javascript - 如何从 ajax 响应执行 javascript 代码?
- java - 如何解决 Spring Boot 项目中 REST 服务的并发问题?
- python - 将域与 DNS 解析器名称匹配 - Python
- javascript - 我在 sublime 文本上运行 javascript 时遇到问题
- reactjs - 创建具有多个 API 调用的 Redux Observable Epic - 将第一个结果传递给第二个
- html - Django 中单个 html 页面中的多个应用程序和视图
- c# - 如何在 C# 中创建包含不同类型的字典类型?
- java - 如何在Java中等待函数内部的函数调用,这可能吗?
- javascript - 如何改进功能中的标志?
- google-cloud-firestore - 如何对数据库中的云 Firestore 文档进行排序?