I want to convert my console application to windows form application.in console form the data is continously coming now i want to display that console output to my richboxtext present in windows form application.assume there is a button,richboxtext in my windows form.please use threads and please look my code below.
using System;
using canlibCLSNET;
namespace CanData02
{
public class Program
{
static void Main(string[] args)
{
int handle;
Canlib.canStatus status;
int channelNumber = 0;
Canlib.canInitializeLibrary();
handle = Canlib.canOpenChannel(channelNumber, Canlib.canOPEN_ACCEPT_VIRTUAL);
CheckStatus((Canlib.canStatus)handle, "canOpenChannel");
status = Canlib.canSetBusParams(handle, Canlib.canBITRATE_250K, 0, 0, 0, 0, 0);
CheckStatus(status, "canSetBusParams");
status = Canlib.canBusOn(handle);
CheckStatus(status, "canBusOn");
DumpMessageLoop(handle);
}
private static void DumpMessageLoop(int handle)
{
Canlib.canStatus status;
bool finished = false;
byte[] data = new byte[8];
int id;
int dlc;
int flags;
long timestamp;
Console.WriteLine("Channel opened. Press Escape to close. ");
Console.WriteLine("ID DLC DATA Timestamp");
while (!finished)
{
status = Canlib.canReadWait(handle, out id, data, out dlc, out flags, out timestamp, 100);
if (status == Canlib.canStatus.canOK)
{
DumpMessage(id, data, dlc, flags, timestamp);
}
else if (status != Canlib.canStatus.canERR_NOMSG)
{
CheckStatus(status, "canReadWait");
finished = true;
}
}
}
private static void DumpMessage(int id, byte[] data, int dlc, int flags, long timestamp)
{
if ((flags & Canlib.canMSG_ERROR_FRAME) != 0)
{
Console.WriteLine("Error Frame received ****");
}
else
{
Console.WriteLine($"{id} {dlc} {data[0]:x2} {data[1]:x2} {data[2]:x2} {data[3]:x2} {data[4]:x2} {data[5]:x2} {data[6]:x2} {data[7]:x2} {timestamp}");
}
}
private static void CheckStatus(Canlib.canStatus status, string method)
{
if (status < 0)
{
Console.WriteLine($"{method} failed: {status.ToString()}");
}
}
}
}
Sam HobbsPosted Jan 25, 2024, 9:51 PM
For Windows Forms the
BackgroundWorkerclass is designed for this type of use. YourDumpMessageLoopwould be theBackgroundWorker.DoWorkevent. TheDoWorkevent executes as a different thread. The output to the window could be sent to the window using theProgressChangedevent and theBackgroundWorkerclass will provide the switching to the UI thread. The documentation provides many examples and there are many relevant articles. Let us know if you have specific questions.Anandu G NathPosted Jan 25, 2024, 12:54 PM
Check Below Refrence code , and change it according to your requirement