I have a vb.net 2008 application that is supposed to send a mouse click to a specified window. This can be any window, and the user selects the correct one from a list box during configuration. The user can also change the window or the mouse button to click at any time.
Everything works fine, window selection, click interval, right or left button, etc. except for one thing. If I move the cursor out of the window, it will click at least one time on whatever window is under the cursor when the event fires, including the desktop.
I have an if statement that checks to see if the window under the cursor is the selected window before firing the mouse event, and it seems to work except for the first click after I leave the window. I call the mouse event based on the timer interval and then check for the correct window within the mouse click subroutine.
Here is the code that calls the timer, the timer, and the mouse click code. Why is it clicking outside the window?
'
' Start the timer and start clicking
'
' numUpDown.Value is set by the user with a NumericUpDown control
Timer1.Interval = numUpDown.Value * 1000 ' Timer runs in milliseconds
Timer1.Enabled = True
Private Sub Timer1_Tick( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles Timer1.Tick
'
' Do not re-initialize blink timer if it
' is already running This timer is used to let the user
' know the click timer is running.
'
If Timer2.Enabled = False Then
Timer2.Interval = 1000 ' One second timer to blink
Timer2.Enabled = True ' red and green
End If
' strMouseAction is set by user to be "R" or "L" for mouse button
Call subMouseClick(strMouseAction)
Application.DoEvents() ' Allow for exit
End Sub
Public Sub subMouseClick(ByVal Action As String)
Dim ptrFGWindow As IntPtr = GetForegroundWindow()
Dim dwFlagsD As Int32 ' mouse button down
Dim dwFlagsU As Int32 ' mouse button up
'
' Check to make sure the proper window is top window
' Do not send mouse clicks to undesired windows
'
' i64Handle is actually hWnd
If i64Handle = ptrFGWindow Then
Select Case Action
Case "L"
dwFlagsD = MOUSEEVENTF_LEFTDOWN
dwFlagsU = MOUSEEVENTF_LEFTUP
Case "R"
dwFlagsD = MOUSEEVENTF_RIGHTDOWN
dwFlagsU = MOUSEEVENTF_RIGHTUP
End Select
mouse_event(dwFlagsD, 0&, 0&, 0, 0)
mouse_event(dwFlagsU, 0&, 0&, 0, 0)
End If
End Sub
If my code looks strange, I'm an old retired programmer from the days when CBASIC was the greatest thing to ever happen to BASIC. All this "Visual" stuff is anything but visual to me, but I'm learning.
Any help would be greatly appreciated.