blah blah blah is here! blah blah » Close

up1down
link

Hi All,

I am working on a bit of software I wrote for Serial Comms I now want an option to allow for the input to read straight out like HyperTerminal did i.e. press 'a' an a is sent out of the port. The software I wrote sends out complete strings rather than piece meal i.e. L500,8,ON is sent as complete string rather than L 5 0 0 , 8 , O N (a < > equals a keypress). The code I have written is shown below. I seem to rember there was a Keypressed event in VB that could be used for this.

private void btnWrite_Click(object sender, EventArgs e)
{

Write_Out_Data();
Thread.Sleep(200);

tmrPollForRecievedData.Enabled = true;
rtbOutgoing.Text = "";
rtbOutgoing.Focus();
}

That is the buttton click here is Write _OutData()
private void Write_Out_Data()
{
textToWrite = rtbOutgoing.Text;// +(char)10 + (char)13;
myComPort.Write(textToWrite);
tmrPollForRecievedData.Enabled = true;
rtbOutgoing.Text = "";
rtbOutgoing.Focus();
}

Thanks
Glenn

last answered one year ago

1 answers

up1down
link

If you're entering the text into a TextBox, then - yes - you can capture each keystroke by handling its KeyPress event.

The following code would only send characters in the ASCII printable range of 32 to 126 to the port and cancel the rest, including backspace. However, on pressing the Enter key, it would send CR + LF to terminate the transmission (if that's what's needed), start the timer to poll for a reply and empty the textbox in readiness for the next string.

private void rtbOutgoing_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)13) // enter key
{
myComPort.Write("\r\n");
Thread.Sleep(200);
tmrPollForRecievedData.Enabled = true;
rtbOutgoing.Text = "";
}
else if (e.KeyChar < 32 || e.KeyChar > 126)
{
e.Handled = true; // ignores anything else outside printable ASCII range
}
else
{
myComPort.Write(e.KeyChar.ToString());
}
}

Notice that this code isn't perfect as the user could still paste stuff into the textbox or move the insertion point with the mouse and mess up the display.

GlennP
329

Yet again its Vulpes! I'll give this ago and get back to you (hopefully positive!) Glenn

GlennP
329

Hi, Seems to do the required! Thanks Glenn

Feedback