|
Here is a nice Com Class that you can use.
using System;
using System.IO.Ports;
using System.Runtime.Remoting.Messaging;
using System.Drawing;
using System.Windows.Forms;
using System.Threading;
namespace ModemAPP
{
public class ComPorts
{
private const string ModuleName = "ComPorts";
internal static bool comPortExists;
internal static string[] myPortNames;
internal static string noComPortsMessage = "No COM ports found. Please attach a COM-port device.";
internal delegate void UserInterfaceDataEventHandler( string action, string formText, Color textColor );
internal static event UserInterfaceDataEventHandler UserInterfaceData;
internal delegate void UserInterfaceResultEventHandler(string strResult);
internal static event UserInterfaceResultEventHandler NumberCrunchInterface;
internal delegate void SerialDataReceivedEventHandlerDelegate( object sender, SerialDataReceivedEventArgs e );
internal delegate void SerialErrorReceivedEventHandlerDelegate( object sender, SerialErrorReceivedEventArgs e );
internal delegate bool WriteToComPortDelegate( string textToWrite );
internal delegate bool ReadComPortDelegate();
delegate void SetTextDeleg(string text);
internal WriteToComPortDelegate WriteToComPortDelegate1;
internal ReadComPortDelegate ReadComPortDelegate1;
private bool m_ParameterChanged;
private bool m_PortChanged;
private bool m_PortOpen;
private SerialPort m_PreviousPort = new SerialPort();
private int m_ReceivedDataLength;
private int m_SavedBitRate = 9600;
private Handshake m_SavedHandshake = Handshake.None ;
private string m_SavedPortName = "";
private SerialPort m_SelectedPort = new SerialPort();
internal bool ParameterChanged
{
get
{
return m_ParameterChanged;
}
set
{
m_ParameterChanged = value;
}
}
internal bool PortChanged
{
get
{
return m_PortChanged;
}
set
{
m_PortChanged = value;
}
}
internal bool PortOpen
{
get
{
return m_PortOpen;
}
set
{
m_PortOpen = value;
}
}
internal SerialPort PreviousPort
{
get
{
return m_PreviousPort;
}
set
{
m_PreviousPort = value;
}
}
internal int ReceivedDataLength
{
get
{
return m_ReceivedDataLength;
}
set
{
m_ReceivedDataLength = value;
}
}
internal int SavedBitRate
{
get
{
return m_SavedBitRate;
}
set
{
m_SavedBitRate = value;
}
}
internal Handshake SavedHandshake
{
get
{
return m_SavedHandshake;
}
set
{
m_SavedHandshake = value;
}
}
internal string SavedPortName
{
get
{
return m_SavedPortName;
}
set
{
m_SavedPortName = value;
}
}
internal SerialPort SelectedPort
{
get
{
return m_SelectedPort;
}
set
{
m_SelectedPort = value;
}
}
private SerialDataReceivedEventHandler SerialDataReceivedEventHandler1;
private SerialErrorReceivedEventHandler SerialErrorReceivedEventHandler1;
internal void CloseComPort( SerialPort portToClose )
{
try
{
if ( null != UserInterfaceData ) UserInterfaceData( "DisplayStatus", "", Color.Black );
object transTemp0 = portToClose;
if ( !( transTemp0 == null ) )
{
if ( portToClose.IsOpen )
{
portToClose.Close();
if ( null != UserInterfaceData ) UserInterfaceData( "DisplayCurrentSettings", "", Color.Black );
}
}
}
catch ( InvalidOperationException ex )
{
ParameterChanged = true;
PortChanged = true;
DisplayException( ModuleName, ex );
}
catch ( UnauthorizedAccessException ex )
{
ParameterChanged = true;
PortChanged = true;
DisplayException( ModuleName, ex );
}
catch ( System.IO.IOException ex )
{
ParameterChanged = true;
PortChanged = true;
DisplayException( ModuleName, ex );
}
}
internal void DataReceived( object sender, SerialDataReceivedEventArgs e )
{
string newReceivedData = null;
try
{
Thread.Sleep(200);
newReceivedData = SelectedPort.ReadExisting();
Thread.Sleep(100);
if (null != UserInterfaceData) UserInterfaceData("Dialing","",Color.Black);
if (newReceivedData.Length > 6)
{
if (null != UserInterfaceData) UserInterfaceData("RetrievingResults", "", Color.Black);
NumberCrunchInterface(newReceivedData);
}
}
catch (Exception ex)
{
DisplayException(ModuleName, ex);
}
}
private void DisplayException( string moduleName, Exception ex )
{
string errorMessage = null;
errorMessage = "Exception: " + ex.Message + " Module: " + moduleName + ". Method: " + ex.TargetSite.Name;
if ( null != UserInterfaceData ) UserInterfaceData( "DisplayStatus", errorMessage, Color.Red );
}
private void ErrorReceived( object sender, SerialErrorReceivedEventArgs e )
{
SerialError SerialErrorReceived1 = 0;
SerialErrorReceived1 = e.EventType;
switch ( SerialErrorReceived1 )
{
case SerialError.Frame:
Console.WriteLine( "Framing error." );
break;
case SerialError.Overrun:
Console.WriteLine( "Character buffer overrun." );
break;
case SerialError.RXOver:
Console.WriteLine( "Input buffer overflow." );
break;
case SerialError.RXParity:
Console.WriteLine( "Parity error." );
break;
case SerialError.TXFull:
Console.WriteLine( "Output buffer full." );
break;
}
}
internal static void FindComPorts()
{
myPortNames = SerialPort.GetPortNames();
if ( myPortNames.Length > 0 )
{
comPortExists = true;
Array.Sort( myPortNames );
}
else
{
comPortExists = false;
}
}
internal bool OpenComPort()
{
bool success = false;
SerialDataReceivedEventHandler1 = new SerialDataReceivedEventHandler(DataReceived);
SerialErrorReceivedEventHandler1 = new SerialErrorReceivedEventHandler(ErrorReceived);
try
{
if ( comPortExists )
{
if ( PreviousPort.IsOpen )
{
CloseComPort( PreviousPort );
}
if ( ( !( ( SelectedPort.IsOpen ) ) | PortChanged ) )
{
SelectedPort.Open();
if ( SelectedPort.IsOpen )
{
SelectedPort.ReadTimeout = 20000;
SelectedPort.WriteTimeout = 20000;
SelectedPort.DataReceived += SerialDataReceivedEventHandler1;
SelectedPort.ErrorReceived += SerialErrorReceivedEventHandler1;
if ( null != UserInterfaceData ) UserInterfaceData( "DisplayCurrentSettings", "", Color.Black );
if ( null != UserInterfaceData ) UserInterfaceData( "DisplayStatus", "", Color.Black );
success = true;
PortChanged = false;
}
}
}
}
catch ( InvalidOperationException ex )
{
ParameterChanged = true;
PortChanged = true;
DisplayException( ModuleName, ex );
}
catch ( UnauthorizedAccessException ex )
{
ParameterChanged = true;
PortChanged = true;
DisplayException( ModuleName, ex );
}
catch ( System.IO.IOException ex )
{
ParameterChanged = true;
PortChanged = true;
DisplayException( ModuleName, ex );
}
return success;
}
internal void WriteCompleted( IAsyncResult ar )
{
WriteToComPortDelegate deleg = null;
string msg = null;
bool success = false;
msg = System.Convert.ToString( ar.AsyncState );
deleg = ( ( WriteToComPortDelegate )( ( ( AsyncResult )( ar ) ).AsyncDelegate ) );
success = deleg.EndInvoke( ar );
if ( success )
{
if ( null != UserInterfaceData ) UserInterfaceData( "UpdateStatusLabel", "", Color.Black );
}
}
internal void ReadComplete(IAsyncResult ar)
{
ReadComPortDelegate deleg = null;
string msg = null;
bool success = false;
msg = System.Convert.ToString(ar.AsyncState);
deleg = ((ReadComPortDelegate)(((AsyncResult)(ar)).AsyncDelegate));
success = deleg.EndInvoke(ar);
if (success)
{
if (null != UserInterfaceData) UserInterfaceData("UpdateStatusLabel", "", Color.Black);
}
Console.WriteLine("Write operation began: " + msg);
Console.WriteLine("Write operation succeeded: " + success);
}
internal bool WriteToComPort( string textToWrite )
{
bool success = false;
try
{
if ( ( !( ( SelectedPort == null ) ) ) )
{
if ( ( ( !( SelectedPort.IsOpen ) ) | PortChanged ) )
{
PortOpen = OpenComPort();
}
}
if ( SelectedPort.IsOpen )
{
SelectedPort.Write( textToWrite );
success = true;
}
}
catch ( TimeoutException ex )
{
DisplayException( ModuleName, ex );
}
catch ( InvalidOperationException ex )
{
DisplayException( ModuleName, ex );
ParameterChanged = true;
if ( null != UserInterfaceData ) UserInterfaceData( "DisplayCurrentSettings", "", Color.Black );
}
catch ( UnauthorizedAccessException ex )
{
DisplayException( ModuleName, ex );
CloseComPort( SelectedPort );
ParameterChanged = true;
if ( null != UserInterfaceData ) UserInterfaceData( "DisplayCurrentSettings", "", Color.Black );
}
return success;
}
internal string ReadComPort()
{
bool success = false;
string dataReadToDisplay = null;
try
{
if ((!((SelectedPort == null))))
{
if (((!(SelectedPort.IsOpen)) | PortChanged))
{
PortOpen = OpenComPort();
}
}
if (SelectedPort.IsOpen)
{
dataReadToDisplay = SelectedPort.ReadLine();
success = true;
}
}
catch (TimeoutException ex)
{
DisplayException(ModuleName, ex);
}
catch (InvalidOperationException ex)
{
DisplayException(ModuleName, ex);
ParameterChanged = true;
if (null != UserInterfaceData) UserInterfaceData("DisplayCurrentSettings", "", Color.Black);
}
catch (UnauthorizedAccessException ex)
{
DisplayException(ModuleName, ex);
CloseComPort(SelectedPort);
ParameterChanged = true;
if (null != UserInterfaceData) UserInterfaceData("DisplayCurrentSettings", "", Color.Black);
}
return dataReadToDisplay;
}
}
}
|
|
|
|
|
Deepak.Prahlad wrote: Timeout value (read timeout and write timeout) every time you read or write
No, timeout is a property just like all others. You can set it once, it will hold its value.
Deepak.Prahlad wrote: Read timeout timer starts when the first characeter arrives at the hardware buffer
No, read timeout starts when a read operation starts. The behavior you are referring to exists in Windows but AFAIK is not exposed to the SerialPort class.
Deepak.Prahlad wrote: thread locking in DataReceived event
DataReceived is an asynchronous event; as such it is handled by a ThreadPool thread, which is not allowed to touch the Winform Controls directly. See this[^] and this[^] article.
One can never be sure that all the serial data that belongs together (a "message") will be received in one go; there always could be a hick-up somewhere, causing the message to be split over two DataReceived events. One approach that often leads to success is by having some delay between the start of the DataReceived event and the actual reading of the data.
|
|
|
|
|
Here's a similar post[^]; maybe it could help.
|
|
|
|
|
Hi stancrm, OriginalGriff, DotNetCoderJunior, Luc Pattyn, PIEBALDconsult
I think I solved the issue by using a thread.sleep() at the bigining of the DataRecieved() as suggested by Luc Pattyn,
Thanks for the help from every one!
Regards
Deepak
|
|
|
|
|
a
modified 23-Nov-14 6:36am.
|
|
|
|
|
You could try creating a class that inherits from the control and provide the functionality there..45 ACP - because shooting twice is just silly ----- "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997 ----- "The staggering layers of obscenity in your statement make it a work of art on so many levels." - J. Jystad, 2001
|
|
|
|
|
If the control is disabled, none of those events fire. Like John said, you'd have to implement your own button class to support this. You'd be creating a button that never really disables. You'd keep track of the Enabled state as in a normal button, and keep certain events running while "disabling" others, like Click DoubleClick, MouseDown, MouseUp, ..., if the control is disabled. You'd also have to custom paint the button to show that it is "disabled" or not.
|
|
|
|
|
bool EverythingYouSaid = PainInTheAss;
bool IsItWorthIt = false; .45 ACP - because shooting twice is just silly ----- "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997 ----- "The staggering layers of obscenity in your statement make it a work of art on so many levels." - J. Jystad, 2001
modified on Friday, March 12, 2010 11:48 AM
|
|
|
|
|
Yep. I didn't say it was worth it, I just said it could be done. Frankly, I can find no value in knowing that the mouse is over a button that's disabled. Sounds like he's trying to use it for something not-so-well-thought-out.
|
|
|
|
|
Evidently, he 1-voted us both. I 5'd you to compensate.
I could almost understand wanting to show tooltips for a control that's disabled.
This particular problem (if done *right*) would require that he create a custom version of every control - a royal pain-in-the-ass. .45 ACP - because shooting twice is just silly ----- "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997 ----- "The staggering layers of obscenity in your statement make it a work of art on so many levels." - J. Jystad, 2001
|
|
|
|
|
John Simmons / outlaw programmer wrote: Evidently, he 1-voted us both. I 5'd you to compensate.
And the same for you!
John Simmons / outlaw programmer wrote: I could almost understand wanting to show tooltips for a control that's disabled.
Yeah, I can see that too... almost. Still, when I see a greyed out control, I don't even bother testing it for some obscure functionality. it just gets skipped until it want's to respond.
John Simmons / outlaw programmer wrote: This particular problem (if done *right*) would require that he create a custom version of every control - a royal pain-in-the-ass.
For some reason, I don't see him doing that.
|
|
|
|
|
It's possible that your application logic may be wrong. Why respond to events on a disabled button? Standard for windows is that disabled objects raise no events, so it has to be some really good reason to go against the flow. Also it will confuse your end users.
As has been said, you could write your own button, but why buck the trend?
|
|
|
|
|
hi..
I need 2 know How i am Insert multiple textbox text in one field
For Example
I have one Field name data
and i have 3 textbox
i want to insert 3 textbox data in one field.
hope u understand my problem
i am waiting your response.
Thanks In advance
Jawad khatri
|
|
|
|
|
I don't get what the problem is?
Where do you fail in your attempt to copy the data from your textboxes?
You access the data in a textbox by using the Text property..
|
|
|
|
|
yes i want to access data to text property
let suppose
i have 3 textboxes
text1.text = I
text2.text = am
text3.text - jawad
now i want to save these 3 textboxes data in one field
|
|
|
|
|
Just concatenate your textbox content to a string:
string theString = string.Empty;
text1.Text = "I";
text2.Text = "am";
text3.Text = "jawad";
theString = text1.Text + text2.Text + text3.Text;
Still not sure if this is what you're after though..
|
|
|
|
|
thanks for response.
i have a table Data have one field name description.
and i have 3 textboxes Rate,Weight,Product
i want to save data of Rate,Weight,Product in description field
Now hope u understand
|
|
|
|
|
Is "Data" a table in a database?
Could you post the code you're having trouble with and describe what goes wrong and what you want it to do?
|
|
|
|
|
Yes Data Is table in database
SqlConnection conn = new SqlConnection(connString);
string query = "insert into Data(Product,discription) values('" + txtproduct.Text + "','" + txtrate.Text + "'&& '" + txtweight.Text + "')";
SqlCommand cmd = new SqlCommand(query, conn);
try
{
conn.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Record Inserted Sucessfully.");
}
finally
{
conn.Close();
}
|
|
|
|
|
Okay, and what is the error your receiving?
Do you really want the concatenated string to look like this (if txtrate=theRating, txtweight=theWeight)?
theRating'&&'theWeight
Or do you want:
theRating&&theWeight
Check the part where you put your strings together.
If you want to use a ' in your concatenated string you have to use double '' like this:
string query = "insert into Data(Product,discription) values('" + textBox1.Text + "','" + textBox2.Text + "''&& ''" + textBox3.Text + "')"; modified on Friday, March 12, 2010 7:01 AM
|
|
|
|
|
I have Done
Thanks For Help Me Sir
|
|
|
|
|
You're welcome
|
|
|
|
|
I am developing some engineering software. It is going quite well and I want to implement network licencing as the copyright protection system for my program. this seems to be the standard for software in my industry basically I believe it works by giving the server a fixed number of licences and it dishes them out to users as required. A popular drafting program, autocad, works like this.
My problem is that I have no idea how to implement this in my program. I am not experianced with dealing with servers and cannot find any example code to work with. I have found code that implements licenceing by handing out a key with the software but it isn't as secure as I would like.
Can anyone help me out with some open source software? Would also be interested in commercial software.
Thanks
|
|
|
|
|
|
thanks very much for the links. I will have a look.
|
|
|
|
|