|
Hi All,
Please find my code below to read the output of two independent temperatures streams.
The form now works well but I cannot close the form when I use the button btnDisconnect_Click at the bottom of the code. The only way I can stop the code is by the stop debugging.
Please can you help
Thank you in advance
Nevjc
Imports System.Drawing.Drawing2D
Imports System.IO.Ports
Public Class Form1
Dim bmp1 As Bitmap = New Bitmap(165, 550)
Dim temperature1 As Double = 10
Dim temperature2 As Double = 10
Dim WithEvents sp As New SerialPort
Private Sub pictherm1_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles pictherm1.Paint
Dim g As Graphics = e.Graphics
g.Clear(Color.White)
If temperature1 > 100 Then temperature1 = 100
g.FillRectangle(Brushes.Green, 48, 525 - CInt(temperature1 * 5), 10, CInt(temperature1 * 5))
If temperature2 > 100 Then temperature2 = 100
g.FillRectangle(Brushes.Green, 108, 525 - CInt(temperature2 * 5), 10, CInt(temperature2 * 5))
g.DrawLine(Pens.Black, 60, 525, 60, 25)
g.DrawLine(Pens.Black, 105, 525, 105, 25)
For i As Integer = 25 To 525 Step 5
g.DrawLine(Pens.Black, 50, i, 60, i)
g.DrawLine(Pens.Black, 105, i, 115, i)
Next
Dim f As Font = New Font("Verdana", 10, FontStyle.Regular)
Dim scale As Integer
For i As Integer = 525 To 25 Step -25
g.DrawLine(Pens.Black, 45, i, 60, i)
g.DrawLine(Pens.Black, 105, i, 120, i)
scale = (525 - i) / 5
g.DrawString(Str(scale), f, Brushes.Black, 65, i - 8)
Next
End Sub
Private Sub btnConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConnect.Click
Try
sp.BaudRate = "9600"
sp.PortName = "COM5"
sp.Open()
If sp.IsOpen Then
btnConnect.Visible = False
btnDisconnect.Visible = True
End If
Catch
sp.Close()
End Try
End Sub
Private Sub Form1_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
If sp.IsOpen() Then
MessageBox.Show("Disconnect before closing")
e.Cancel = True
End If
End Sub
Delegate Sub myMethodDelegate1(ByVal [text] As String)
Dim myDelegate1 As New myMethodDelegate1(AddressOf ProcessReading1)
Private Sub SerialPort_DataReceived1(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles sp.DataReceived
Dim str1 As String = sp.ReadLine()
Dim firststr As String = Mid(str1, 1, 4)
Invoke(myDelegate1, firststr)
End Sub
Sub ProcessReading1(ByVal input As String)
If IsNumeric(input) Then
temperature1 = CDbl(input)
lblLeft.Text = CDbl(temperature1)
pictherm1.Refresh()
End If
End Sub
Delegate Sub myMethodDelegate2(ByVal [text] As String)
Dim myDelegate2 As New myMethodDelegate2(AddressOf ProcessReading2)
Private Sub SerialPort_DataReceived2(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles sp.DataReceived
Dim str2 As String = sp.ReadLine()
Dim secondstr As String = Mid(str2, 6, 5)
Invoke(myDelegate2, secondstr)
End Sub
Sub ProcessReading2(ByVal input As String)
If IsNumeric(input) Then
temperature2 = CDbl(input)
lblRight.Text = CDbl(temperature2)
lblTotal.Text = CDbl(temperature1 + temperature2)
lblDiff.Text = CDbl(temperature1 - temperature2)
pictherm1.Refresh()
End If
End Sub
Private Sub btnDisconnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisconnect.Click
Try
sp.Close()
btnConnect.Visible = True
btnDisconnect.Visible = False
Exit Sub
Catch
MessageBox.Show("Some kind of problem.")
End Try
End Sub
End Class
|
|
|
|
|
What about this.Close(); or Application.Exit(); ?
|
|
|
|
|
Hi Berhard,
Thankyou for the suggestion. Both those work when you have just opened the form but as soon as you start reading the serial port they dont work. It appears that the infomation from the serial port is holding the form open.
Any other suggestions?
Regards
Nevjc
|
|
|
|
|
I would try the following modifications to the DataReceived event handlers
Private Sub SerialPort_DataReceived1(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles sp.DataReceived
Try
Dim str1 As String = sp.ReadLine()
Dim firststr As String = Mid(str1, 1, 4)
Invoke(myDelegate1, firststr)
BeginInvoke(myDelegate1, firststr)
Catch ioex As IOException
System.Diagnostics.Debug.Print("IOException {0}", ioex.Message)
EndTry
End Sub
If ReadLine is blocked waiting for data then issuing a Close request on the SerialPort will cause an IOException to be thrown with the message "Serial port is Closed". I don't know if that will be causing a problem but the Try.. Catch will let you see what's happening.
Replacing Invoke with BeginInvoke can only do good as it will allow the UI thread to invoke the delegate when it is not busy. If the problem is a deadlock then this change will definitely help.
Alan.
|
|
|
|
|
Hi Alan,
Thanks for that.
I have changed the Invoke to BeginInvoke and there is an improvement in operation ie the btnconnect button returns as it should occasionally.
The form also occasionally closes and themessage returned is "IO Eception was unhandled" is reported and the Dim str1 As String =sp.Readline() is yellowed out.
Does this help?
Regards Nevjc
|
|
|
|
|
Premise that I do not have much experience with visual basic!
I need to make a chart from a csv file that is structured like this:
"VarName", "TimeString", "Temperature", "Validity", "Time_ms"
"var_1", "04/02/2014 04:40:29", 115.5, 1, 41,731,194,780.0926
"var_3", "04/02/2014 04:42:37", 27.4, 1, 41,731,196,261.5741
"var_2", "04/02/2014 04:42:37", 83.2, 1, 41,731,196,261.5741
"var_1", "04/02/2014 04:42:37", 115.8, 1, 41,731,196,261.5741
note that "VarName" are listed in no particular order.
What I would like is to be able to choose the "VarName" via a ComboBox and via a DateTimePicker the day, so as to produce a chart with "TimeString" on the X axis and "Temperature" on Y.
If can be done you can help me, I dont know where to start.
Sorry for my english :-O
Thank you!
|
|
|
|
|
Member 10735492 wrote: I dont know where to start. Given your first sentence, I would suggest studying more VB.NET, and some of the articles at http://www.codeproject.com/KB/vb/[^].
|
|
|
|
|
Member 10735492 wrote: What I would like is to be able to choose the "VarName" via a ComboBox and via a DateTimePicker the day, so as to produce a chart with "TimeString" on the X axis and "Temperature" on Y. You'd start by finding a tutorial on using the chart. I don't know whether you're using WinForms, ASP, WPF or Gtk. But assuming your using either WinForms or ASP, you'd start here[^].
I'd also recommend against charting directly from a CSV; the file-format is meant for exports, not as a datastore that one would query often.
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
Hell every one
I converted my vb6 project to vb.net and having this error.
My code is
Public Function CenterMessageBox(ByRef frmHwnd As Integer) As Object
Dim lInstance As Integer
Dim lThreadID As Integer
lInstance = GetWindowLong(frmHwnd, GWL_HINSTANCE)
lThreadID = GetCurrentThreadId()
plMsgHook = SetWindowsHookEx(WH_CBT, AddressOf CenterMsgCallBack, lInstance, lThreadID)
End Function
and
Private Function CenterMsgCallBack(ByVal lMsg As Integer, ByVal wParam As Integer, ByVal lParam As Integer) As Integer
Dim typFormRect As RECT
Dim typRectMsg As RECT
Dim lxPos, lyPos As Integer
If lMsg = HCBT_ACTIVATE Then
GetWindowRect(frmMain.Handle.ToInt32, typFormRect)
GetWindowRect(wParam, typRectMsg)
lxPos = (typFormRect.Left_Renamed + (typFormRect.Right_Renamed - typFormRect.Left_Renamed) / 2) - ((typRectMsg.Right_Renamed - typRectMsg.Left_Renamed) / 2)
lyPos = (typFormRect.Top + (typFormRect.Bottom - typFormRect.Top) / 2) - ((typRectMsg.Bottom - typRectMsg.Top) / 2)
SetWindowPos(wParam, 0, lxPos, lyPos, 0, 0, SWP_NOSIZE Or SWP_NOZORDER Or SWP_NOACTIVATE)
UnhookWindowsHookEx(plMsgHook)
End If
CenterMsgCallBack = False
End Function
Please tell me what to do. I don't know this programming language and i have searched the answer of it but not getting how to implememt. Please help I will be thankful to you
|
|
|
|
|
That's some really old code - I'm guessing it came from this[^], which says it was written for VB5.
The immediate problem is that you're trying to pass a callback delegate as a Integer . You can't do that in VB.NET; you have to pass it as a delegate instead.
A lot of the parameters that you're passing as Integer need to be IntPtr to work properly in 64-bit applications. You can usually get a good declaration for the P/Invoke methods from pinvoke.net[^].
The code also never calls CallNextHookEx , which you're supposed to call from the hook callback method.
The following code should work:
Imports System.Runtime.InteropServices
Module MsgBoxHelper
<StructLayout(LayoutKind.Sequential)> _
Private Structure RECT
Public ReadOnly Left As Integer
Public ReadOnly Top As Integer
Public ReadOnly Right As Integer
Public ReadOnly Bottom As Integer
End Structure
Private Delegate Function HookProc(ByVal code As Integer, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As IntPtr
<DllImport("user32.dll", SetLastError:=True)> _
Private Function SetWindowsHookEx(ByVal hookType As Integer, ByVal lpfn As HookProc, ByVal hMod As IntPtr, ByVal dwThreadId As Integer) As IntPtr
End Function
<DllImport("user32.dll")> _
Private Function CallNextHookEx(ByVal hhk As IntPtr, ByVal nCode As Integer, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As IntPtr
End Function
<DllImport("user32.dll", SetLastError:=True)> _
Private Function UnhookWindowsHookEx(ByVal hhk As IntPtr) As Boolean
End Function
<DllImport("user32.dll", SetLastError:=True)> _
Private Function GetWindowLong(ByVal hWnd As IntPtr, ByVal nIndex As Integer) As IntPtr
End Function
<DllImport("kernel32.dll")> _
Private Function GetCurrentThreadId() As Integer
End Function
<DllImport("user32.dll")> _
Private Function GetWindowRect(ByVal hWnd As IntPtr, ByRef lpRect As RECT) As Boolean
End Function
<DllImport("user32.dll", SetLastError:=True)> _
Private Function SetWindowPos(ByVal hWnd As IntPtr, ByVal hWndInsertAfter As IntPtr, _
ByVal X As Integer, ByVal Y As Integer, ByVal cx As Integer, ByVal cy As Integer, ByVal uFlags As Integer) As Boolean
End Function
Private Const GWL_HINSTANCE As Integer = -6
Private Const HCBT_ACTIVATE As Integer = 5
Private Const SWP_NOSIZE As Integer = &H1
Private Const SWP_NOZORDER As Integer = &H4
Private Const SWP_NOACTIVATE As Integer = &H10
Private Const WH_CBT As Integer = 5
Private theForm As IWin32Window
Private plMsgHook As IntPtr
Public Sub CenterMessageBox(ByVal parentForm As IWin32Window)
If parentForm Is Nothing Then
Throw New ArgumentNullException("parentForm")
End If
If plMsgHook <> IntPtr.Zero Then
Throw New InvalidOperationException("The hook is already installed.")
End If
theForm = parentForm
Dim lInstance As IntPtr = GetWindowLong(parentForm.Handle, GWL_HINSTANCE)
Dim lThreadID As Integer = GetCurrentThreadId()
plMsgHook = SetWindowsHookEx(WH_CBT, AddressOf CenterMsgCallBack, lInstance, lThreadID)
End Sub
Private Function CenterMsgCallBack(ByVal code As Integer, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As IntPtr
If code = HCBT_ACTIVATE Then
Dim typFormRect As RECT
Dim typMsgRect As RECT
Dim lxPos As Integer, lyPos As Integer
GetWindowRect(theForm.Handle, typFormRect)
GetWindowRect(wParam, typMsgRect)
lxPos = CInt((typFormRect.Left + (typFormRect.Right - typFormRect.Left) / 2) - ((typMsgRect.Right - typMsgRect.Left) / 2))
lyPos = CInt((typFormRect.Top + (typFormRect.Bottom - typFormRect.Top) / 2) - ((typMsgRect.Bottom - typMsgRect.Top) / 2))
SetWindowPos(wParam, IntPtr.Zero, lxPos, lyPos, 0, 0, SWP_NOSIZE Or SWP_NOZORDER Or SWP_NOACTIVATE)
UnhookWindowsHookEx(plMsgHook)
plMsgHook = IntPtr.Zero
theForm = Nothing
End If
Return CallNextHookEx(IntPtr.Zero, code, wParam, lParam)
End Function
End Module
To call it:
CenterMessageBox(Me)
MessageBox.Show("This is a centered Message Box")
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Hello !
I have a binding source to entity :
MyBindingsource.datasource=(From t in context.Mytable Select t.id , t.vl1 , t.vl2).Tolist
Now , I try to change a value like this :
Mybindingsource.Current.vl1=25
I get a n error :
An unhandled exception of type 'System.MissingMemberException' occurred in Microsoft.VisualBasic.dll
Additional information: Property 'vl1' is ReadOnly.
Why I get this error ? What can I do ?
Thank you !
|
|
|
|
|
vl1 is a property in a class. It does not have a set accessor, i.e. your property looks something like
public int vl1
{
get { return ...; }
}
insetad of
public int vl1
{
get { return ...; }
set { ...; }
}
|
|
|
|
|
Why does not have a set ?
Because , if I try the following code everything works ok :
MyBindingsource.datas
ource=(From t in context.Mytable Select t).Tolist
Why this :
MyBindingsource.datasource=(From t in context.Mytable Select t.id , t.vl1 , t.vl2).Tolist doesn't work ?
Thank you !
|
|
|
|
|
dilkonika wrote: Because , if I try the following code everything works ok : That's different code; the setter isn't used there. The code below, as you posted, would raise that exception - if it is a read-only property.
Mybindingsource.Current.vl1=25
dilkonika wrote: MyBindingsource.datasource=(From t in context.Mytable Select t.id , t.vl1 , t.vl2).Tolist Does it throw the SAME exception? I don't see it assigning anything to vl1 and doubt that it will throw the same error.
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
If I use
MyBindingsource.datasource=(From t in context.Mytable Select t).Tolist
and after :
Mybindingsource.Current.vl1=25
everything is ok.
|
|
|
|
|
dilkonika wrote:
If I use
MyBindingsource.datasource=(From t in context.Mytable Select t).Tolist
and after :
Mybindingsource.Current.vl1=25 everything is ok.
Is it the same Mytable? Apparently this one has a field for vl1 that is assignable - as in, not a view.
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
|
It's "something" in the EF framework. The first query is a simple one, and it may generate a decent update-statement for it- while that may be a bit harder for the second query.
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
I am writing a code for my CIS-115 class. I have all of the information that I need in it (I think!), but I cannot get ALL of my calculations to execute correctly; only 2 of 5 come out right. Am I allowed to post it here to get help?
|
|
|
|
|
Yes, but don't ask for anyone to write your code for you. That's the restriction.
|
|
|
|
|
You will need to design an application that will receive the customer type and its units of utility used for the billing duration. The application will calculate and display the cost per unit based on the customer type and the total charges for that billing cycle. Calculate the charges using the following data.
Customer Type Units Consumed Cost per unit ($)
Commercial <= 1,000 $0.50 per unit
Commercial 1,000 < $0.50 per unit
Industrial < 800 $0.65 per unit
Industrial 800 <= 2,000 $0.55 per unit
Industrial 2,000 < $0.50 per unit
Residential < 500 $0.85 per unit
Residential 500 <= $0.75 per unit
Make sure that the units consumed entered is a positive number and the customer Type is valid; otherwise your program should display an error message and ask for the data to be entered again until the user enters valid data. Test your algorithm with the following three sets of data.
Test case 1: Units used of 799, Customer Type is Industrial
Test case 2: Units used 500, Customer Type is Residential
Test case 3: Units used 800, Customer Type is Industrial
Test case 4: Units used 1000, Customer Type is Commercial
Test case 5: Units used 499, Customer Type is Residential
|
|
|
|
|
Sub Main()
Dim customerType As String
Dim unitsConsumed As Decimal = 0
Dim costPerUnit As Decimal = 0
Dim totalCharges As Decimal = 0
Do
Console.Write("Enter the customer type as commercial, industrial, or residential: ")
customerType = Console.ReadLine()
While customerType <> "commercial" And customerType <> "industrial" And customerType <> "residential"
Console.WriteLine("ERROR - Enter commerical, industrial, or residential.")
Console.Write("Enter the customer type as commercial, industrial, or residential: ")
customerType = Console.ReadLine()
End While
Console.Write("Enter the units consumed: ")
unitsConsumed = Console.ReadLine()
While unitsConsumed < 0
Console.WriteLine("ERROR - Please enter a value greater than zero.")
Console.Write("Enter the units consumed. ")
unitsConsumed = Console.ReadLine()
End While
If unitsConsumed <= 1000 Then
costPerUnit = 0.5
If unitsConsumed < 1000 Then
costPerUnit = 0.5
If unitsConsumed < 800 Then
costPerUnit = 0.65
If (unitsConsumed > 800) And (unitsConsumed <= 2000) Then
costPerUnit = 0.55
If unitsConsumed > 2000 Then
costPerUnit = 0.5
If unitsConsumed < 500 Then
costPerUnit = 0.85
If unitsConsumed >= 500 Then
costPerUnit = 0.75
End If
End If
End If
End If
End If
End If
End If
totalCharges = unitsConsumed * costPerUnit
Console.WriteLine("The total charges are: " & totalCharges)
Console.ReadLine()
Loop
End Sub
|
|
|
|
|
This is the code that I have, but only Test Case 1 and 4 execute correctly. I have sat here for hours looking through my book and lectures, but I'm just blind to my problem. Thank you, in advance, if you are able to help me!
|
|
|
|
|
Look at your nested if statement 100 meets these criteria 1000, 1000, 800 500 so which value will be returned, the first of course.
Never underestimate the power of human stupidity
RAH
|
|
|
|
|
Another day, another hint.
If x < 1000 Then
If x < 800 Then
If x > 2000 Then
End If
End If
End If Find me a number smaller than 1000, but larger than 2000.
There's another problem, take a look at the example-rules;
Member 10728667 wrote: Commercial <= 1,000 $0.50 per unit
Commercial 1,000 < $0.50 per unit If think the first price is for commercial stuff if you buy 1000 items or less, and the second price would be if you buy MORE than 1000 items. That's prolly what the position of the operator should imply. Back to the code;
If unitsConsumed <= 1000 Then
costPerUnit = 0.5
If unitsConsumed > 1000 Then
Now that I switched the operator to what it probably should be, does it help to diagnose the error?
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|