Sending a message to any windows textbox just by focus - vb.net

I need to know how I can send a message to any text box of windows.
If a focus the google chrome url textbox, then I will "auto paste" the message, or if I focus a Word Document string, or notepad, or anything!
I got a code ho sends by setting the iHwnd, findwindow and findwindowex, but I need to set any time I want to change the final program, and thats why I need an automatic program "focus based".
Here is what I have so far...
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim iHwnd As IntPtr = FindWindow("notepad", vbNullString)
Dim iHwndChild As IntPtr = FindWindowEx(iHwnd, IntPtr.Zero, "Edit", vbNullString)
SendMessage(iHwndChild, WM_SETTEXT, 0, "Hello World!")
End Sub
Sorry for my bad english!

SendMessage is always going to require a specific window handle, or broadcast to all top level windows. To continue with your current code, you could first try to retrieve the active window's handle with GetActiveWindow or similar function.
Alternately, you could experiment with the SendKeys class to send your text. SendKeys always targets the currently active control (as if the user were typing directly on the keyboard), so you don't need to concern yourself with finding window handles or titles.

Related

Disable iBeam pointer in TextBox using VB.NET

I am currently working on a TextBox using VB.NET 2015 that is read-only and only inserts characters by a button click event. I want to hide or disable the iBeam inside the TextBox to let the user know that it is only accessible by the button click and not by manual typing on the actual keyboard. I have tried changing its ReadOnly property to True and cursor property to cursors other than the iBeam but they don't seem to work.
Is there another way, may it be a code or a property that disables the iBeam in the TextBox when its accessed?
This image is my example of an on-screen keyboard. As you can see, the iBeam on the TextBox is visible as soon as I click on one of the on-screen keys.
Use the HideCaret() API call from the GotFocus() event of your TextBox:
Private Declare Function HideCaret Lib "user32.dll" (ByVal hWnd As IntPtr) As Boolean
Private Sub TextBox1_GotFocus(sender As Object, e As EventArgs) Handles TextBox1.GotFocus
HideCaret(TextBox1.Handle)
End Sub

VB.NET Events not Firing

I've received a project from another developer. Long story short, the program pulls several thousand entries from an SQL Database hosted on our internal network. The program displays the entries and allows you to filter them for convenience.
Recently we had an issue in which a table in our SQL Database was cleared (It's normally regenerated each day, but for several days it was blank.) Found the issue and solved it (Made no changes to the VB project) to repopulate the table; but since that point the VB project would no longer fire events.
The program is several thousand lines of code long, so I can not post the entire thing; but I will try my best to give symptoms:
The form object can fire events (Form_Closing, Form_Closed, etc.)
The existing controls (Radio button, buttons, picturebox, data grid view, etc) will not fire any events.
If I add a new control (such as a button), it will not fire events.
If a put a debug breakpoint at the sub that should be fired, it will not break.
Here's an example of a method that should be fired but is not fired:
`Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
MsgBox("GOT IT!")
End Sub`
Here's the Form_Load sub:
<DllImport("user32.dll")> _
Private Shared Function SendMessage(ByVal hWnd As IntPtr, ByVal wMsg As Integer, ByVal wParam As Integer, ByVal lParam As Integer) As Integer
End Function
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
InitializeComponent()
Try
DataGridView_Items.RowsDefaultCellStyle.SelectionBackColor = Color.Yellow
DataGridView_Items.RowsDefaultCellStyle.SelectionForeColor = Color.Black
CheckBox_Highlight.DataBindings.Add("Visible", RadioButton_BD, "Checked")
Try
'Populates the DGV
LoadTable()
TableLayoutPanel_BD_Parts.Visible = True
TableLayoutPanel_PF_Parts.Visible = False
'Exits if no data was pulled from the database
If dbDataSet.Rows.Count = 0 Or pfDataSet.Rows.Count = 0 Then Application.ExitThread()
Catch ex As Exception
Using w As StreamWriter = File.AppendText(logFile)
Log("Function Form1_Load says " & ex.Message & " # " & DateTime.Now.ToString("yyyy-MM-dd") & "_" & DateTime.Now.ToString("HH-mm-ss"), w)
End Using
End Try
BackgroundWorker1.RunWorkerAsync()
formLoaded = True
Catch exx As Exception
MsgBox(exx.ToString())
End Try
End Sub
There is a backgroundworker, but it appears to work correctly and exit out.
All the forms can be interacted with; but do not fire events. (I can change the selection of the radio button, click the button, type into text boxes, etc.)
I know this is a little vague, I'm just hoping someone can give suggestions as to things that could cause this that I can look into. I can provide specifics; but I can't copy the entire code here.
Thanks for any help!
A very strange thing in your code is that you call InitializeComponent() from Form_Load.
Usually this method is called in Form constructor so you can remove it from Form_Load.
I made some test on my PC: if you called twice InitializeComponent() you duplicate every controls in the form and their events doesn't fire anymore maybe because you have two controls with the same name.

VB.net (2010) Click-through on all controls

I'm having a application with quite a few tabpages. One function of my program is that if the user leaves the application for more than 3 minutes, I display the main tabpage where the most relevant information is shown (this is done by a timer called "back_to_main_tab"). So far so good. However in a few tabpages you can enter text and "take a pause" for more than these 3 minutes, and if that happens, the user is taken back to the main tab, without his/her consent, erasing his/her entered text.
I realize that this could be solved by enabling/disabling the back_to_main_tab-timer at strategic places, but I would like to solve it by resetting the timer each time a click is registered in the application regardless of what is is clicked. The reason for this is that the problem isn't unique for a certain tabpage, so I would like to have a "all-purpose"-fix for all tabpages.
Is this possible?
Thanks in advance
Jonas
You can write an Event Handler for each element where user can write.
For example
Private Sub TextBox1_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDown
'Reset timer
End Sub
(and you could try KeyUp or KeyPress too).
So you can reset timer each time the user write something somewhere.
Btw if the 3mins pass (after last KeyPress), the back_to_main_tab erase all.
EDIT
Ok so you could make one function to Manage the CLICK event. And attach the function to all items form.
To attacch an event handler to alla element you could try something like this
Private Sub AddGenericEventHandler()
For Each Ctrl As Item In Form.Items
AddHandler Ctrl.Click, AddressOf MyClickHandler
Next
End Sub
And write the function that reset your timer
Public Sub MyClickHandler(ByVal sender As System.Object, ByVal e As System.EventArgs)
'Timer Reset
End Sub
This is an Idea. You have to write correctly the FOR EACH to catch all form items do you need.

vb.net how to solve 2 issues with single and double click on notify icon

I have a vb.net (.NET 3.0) app which has a NotifyIcon in the system tray. I would like the single left-click and double left-click events to do different things; .Click should open the app's context menu, and .DoubleClick should take some default action. So this is my code at the moment:
Private Sub showMenu(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) _
Handles Tray.Click
Debug.Print("click")
If e.Button = MouseButtons.Left Then
Dim mi As MethodInfo = GetType(NotifyIcon).GetMethod("ShowContextMenu", BindingFlags.Instance Or BindingFlags.NonPublic)
mi.Invoke(Tray, Nothing)
End If
End Sub
Private Sub defaultAction(ByVal sender As System.Windows.Forms.NotifyIcon, ByVal e As System.EventArgs) _
Handles Tray.DoubleClick
Debug.Print("double click")
doDefaultAction()
End Sub
The first problem is that the .Click handler is fired even for a double-click - it responds to the first click rather than waiting to see if it was actually a double-click. Maybe this is normal behaviour, but is there a 'best practice' way of trapping that occurrence without horrible kludges involving timers? From what I've read on SO, I suspect not. However, that's not the most serious problem...
The second, bigger, problem is that the doDefaultAction() code does various things, one of which is to download an xml file from a specific URL. I'm doing this with this line of code (note not the actual URL:):
Dim reader = XmlReader.Create("http://server.com/genxml.php")
As soon as execution reaches that line, another .Click event is fired, so the debug output looks like this:
click
double click
click
That second click event re-opens the context menu, and because doDefaultAction() goes on to show a modal MessageBox, the menu gets stuck open. I've stepped through in the debugger, and if I 'Step Into' that Dim reader line, I get taken straight to Sub showMenu() above. Very odd. Any ideas what could cause that?

VB 2012 TextBox.Clear() not working

I'm working on an encryption program and it uses a "PIN" to calculate some stuff for the encryption. I have a textbox where the user can insert the "PIN". I'd like to prevent people from entering anything but numbers. I added this on the KeyPress event:
If Not Char.IsControl(e.KeyChar) Then
If Not Char.IsNumber(e.KeyChar) Then
MsgBox("Invalid character", , "WARNING!")
TextBox3.Clear()
End If
End If
It shows the msgbox and it doesn't write to the textbox until i close th emsgbox. The typed character appears in the textbox. When I write another one it works the same as before, but it only replaces the last character instead of writing another one. Is there something I'm missing because that looks like a bug to me?
Set the ES_NUMBER windows style for your TextBox:
Public Class Form1
Public Const GWL_STYLE As Integer = (-16)
Public Const ES_NUMBER As Integer = &H2000
Public Declare Function GetWindowLong Lib "user32" Alias "GetWindowLongA" _
(ByVal handle As IntPtr, ByVal nIndex As Integer) As Integer
Public Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" _
(ByVal handle As IntPtr, ByVal nIndex As Integer, ByVal dwNewLong As Integer) As Integer
Public Sub SetNumbersOnlyTextBox(ByVal TB As TextBox)
SetWindowLong(TB.Handle, GWL_STYLE, GetWindowLong(TB.Handle, GWL_STYLE) Or ES_NUMBER)
End Sub
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
SetNumbersOnlyTextBox(TextBox3)
End Sub
End Class
It shows the msgbox and it doesn't write to the textbox until i close th emsgbox.
Yes, that's what modal dialogs do. They block the caller from updates until closed. That's the point; the user cannot interact with the parent until they clear the modal child.
Why not simply clear the textbox first? Better yet; don't show an annoying dialog at all. Simply disallow the user from entering invalid characters by setting e.Handled to true. However, it's a bit trickier than it sounds as you need to allow for the backspace and delete keys, disable pasting, etc.
Here's an example of a NumericTextbox: http://msdn.microsoft.com/en-us/library/ms229644(v=vs.80).aspx
You just need to set the Handled property to true instead of clear:
e.Handled = True
As MarkPM notes above, if its a key you don't want you can set e.handle=true (as you intercept the key on the keypress event) to have the system eat it.
Along with this, in stead of a pop-up, you can have a label on the form that says "Only numbers can be entered here" or something like that. Set it up so that the color of the text is red. Also set it up so the label is not normally visible.
Finally, also in the keypress event, beyond setting e.handle=true for unwanted keys, when an unwanted key comes along make the label that says "Only numbers can be entered here" visible - you can also set up a timed event to turn the label's visibility off after a few seconds. You can also throw a Beep() into the mix if you like :-)
This is less invasive then a pop-up and moves things along nicely for the user.