The problem you're seeing with App.PrevInstance
might be because you're testing with the application running under the debugger (i.e., the VB 6 IDE). But I'm not entirely sure. It might just perform the check once and cache the value, which allows it to grow "stale" as the environment state changes. As you've already noticed, the App.PrevInstance
property has a lot of limitations. Another common problem with it is its fragility. Changing the name of the executable is an easy way to make it fail. That is not always the desired behavior.
So it's a good idea to replace it with an alternative solution. Like wqw says in a comment, the best solution would be to create a mutex using a GUID for the name of the mutex whenever your application starts up. This should succeed the first time, but will fail subsequently because the mutex is already registered (by a previous instance of your application). That failure is your clue that a previous instance of your application is running. To do this in VB 6, you will need to import and call some Win32 functions, like CreateMutex
, CloseHandle
, and ReleaseMutex
. There's a sample of how to use mutexes on MSDN, but that won't help you very much to write VB 6 code unless you are already rather familiar with the Win32 API. I've linked to a tutorial that contains the necessary code in VB 6 in my answer here.
If you're otherwise satisfied with the behavior of App.PrevInstance
and you just want it to perform the check each time you call it (rather than using a stale cached value), then you can just replace it with a call to your own function that does essentially the same thing: iterate through all of the currently-running processes, and look for a match to the name of your executable. Unfortunately, this is not necessarily less work than the "better" solution involving the use of a mutex. You'll still need to import a number of Win32 functions, including EnumProcesses
. There are instructions for this in an old knowledge base article—obviously you want to focus on the "Windows NT" section and ignore the "Windows 95/98" stuff.
I guess that for this you would need the date/time processes started to be available. As this information does not seem to be available from the task manager I wonder if windows stores it at all?
You don't actually need this information. In fact, I'm not sure what approach you had in mind that would require it. It doesn't matter when the process was started, it just matters whether or not it is currently running. Those are two completely different things.
However, just for fun, Windows does in fact store this information. Task Manager doesn't show it, but Process Explorer does. You can retrieve it programmatically either by calling the GetProcessTimes
function, or querying WMI (specifically, the CreationDate
property of the Win32_Process
class).