Suppose you have an editor named OnlyOne.exe. When you click and drag .txt files onto OnlyOne.exe, this editor opens and displays the file(s) in separate MDI child windows.
Now suppose OnlyOne.exe is already running and you click and drag a .txt file onto OnlyOne.exe. Instead of opening again, you want to have the running instance of the program open the newly dragged files.
How do you do that?
A program can use App.PrevInstance to see if another instance of the program is already running.
- Check App.PrevInstance to see if an existing instance is running. If an existing instance is running:
- Tell that application to open the new files.
- Activate the existing instance.
- If no existing instance is running:
- Open the new files.
The tricky part is telling the existing instance to open the files.
The program contains a PictureBox in its MDI form. Inside that control is a TextBox named txtCommand. The program sends the file names to the existing instance by using the SendMessage API function to put the names in the existing instance's copy of txtCommand. Then the txtCommand_Change event handler sees the new names and loads the files.
Once it knows there is an existing instance of the program, the program uses the FindWindow API function to get that instance's window handle.
Next it uses the GetWindow API function to traverse the window's child windows looking for one that has a class name starting with "Thunder" and ending with "PictureBoxDC". This is the PictureBox inside the MDI form. In VB6, this window's class name is "ThunderPictureBoxDC" at design time and "ThunderRT6PictureBoxDC" at run time. By searching for the start and end of the class name instead of the exact name, this program should hopefully work at design time or run time in different vesions of Visual Basic. The FindChildByClassPrefixAndPostfix routine in the program wraps this search up so it's easy to use.
Next the program performs a similar search of the PictureBox's children looking for one with class name starting with "Thunder" and ending with "TextBox". This is txtCommand.
To prevent trouble in case another program has just set txtCommand's value, the program then uses the GetWindowText API function to get txtCommand's value. It keeps looking until the value is blank. Then it uses SendMessage to drop the file names into txtCommand.
Having passed the file names to the existing instance, the new instance unloads itself.
- Using FindWindow to get a window with a known title
- Using GetWindow to traverse the main window list
- Using GetWindow to traverse a window's chidlren
- Using GetClassName to get a window's class name
- Using GetWindowText to get a window's text
- Using SendMessage to set a window's text
Outstanding question: Does anyone know how to get a window's name from its handle? In this case, txtCommand's name?