如何在C#中使用withevents [英] How to use withevents in C#

查看:348
本文介绍了如何在C#中使用withevents的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我找到代码来自

hi everyone,
I find code from

Sigurd Johansen

谈谈

NET中串口的通讯2.0



进口系统

进口System.IO.Ports



公开Class Form1

Dim WithEvents Port As SerialPort = _

新SerialPort(COM1,9600,Parity.None,8,StopBits.One)

Private Sub btnSendText_Click(ByVal sender As System.Object,_

ByVal e As System.EventArgs)处理btnSendText.Click

Port.Open()

Port.Write(txtSendText.Text&!%)

Port.Close()

结束子

结束上课



我想用C#asp.net写它。有人可以帮助我。

谢谢。



我的尝试:



talk about
Communication on a serial port in NET 2.0

Imports System
Imports System.IO.Ports

Public Class Form1
Dim WithEvents Port As SerialPort = _
New SerialPort("COM1", 9600, Parity.None, 8, StopBits.One)
Private Sub btnSendText_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnSendText.Click
Port.Open()
Port.Write(txtSendText.Text & "!%")
Port.Close()
End Sub
End Class

I want write it in C# asp.net. Someone can help me.
thanks.

What I have tried:

Imports System
Imports System.IO.Ports

Public Class Form1
Dim WithEvents Port As SerialPort = _
New SerialPort("COM1", 9600, Parity.None, 8, StopBits.One)
Private Sub btnSendText_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnSendText.Click
Port.Open()
Port.Write(txtSendText.Text & "!%")
Port.Close()
End Sub
End Class

推荐答案

你好tanliem653,



没有必要相当于<$ c在这种情况下,$ c> WithEvents 。 C#的等价物是:

Hi tanliem653,

There is no need for the equivalent of WithEvents in this case. The C# equivalent is:
using System.Windows.Forms;
using System.IO.Ports;

public partial class Form1 : Form
{
    SerialPort Port = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);

    private void btnSendText_Click(object sender, EventArgs e)
    {
        Port.Open();
        Port.Write(txtSendText.Text + "!%");
        Port.Close();
    }
}

实际上在这种情况下,VB.NET代码也不需要 WithEvents 。只有在需要添加自定义事件处理程序时才需要它。例如:

Actually in this case, the VB.NET code doesn't need WithEvents either. It is only needed if there is a need to add a custom event handler. E.g.:

Private Sub MyPortAction(sender As Object, e As EventArgs) Handles Port.Disposed
......
......
End Sub


这篇关于如何在C#中使用withevents的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆