I have a 32 bit application that shells a second application that can be 32 or 64-bit depending upon the computer it's running on.
I only want one instance of the second application to run at a time, and I need the first application to prevent the second from being launched more than once.
I want to be able to use GetProcessesByName to obtain the runn开发者_如何转开发ing processes. This seems to work fine. It's when I attempt to obtain the module data to find out what folder the second application was run from that things fall apart.
Does anyone have a suggestion for identifying 64-bit processes and their folder of origin from a 32-bit application?
Thank you, SH
You can use the WMI API (System.Management
namespace) for this, specifically the ManagementObjectSearcher. The example below shows to get the process id and full command line from all running notepad instances.
Imports System.Management
Module Module1
Sub Main()
Dim wmi = New ManagementObjectSearcher("SELECT ProcessId, CommandLine FROM Win32_Process WHERE CommandLine LIKE ""%notepad%""")
Dim result = wmi.Get().OfType(Of ManagementObject)()
For Each r In result
Console.WriteLine("Process ID: {0}, Command Line: {1}" r("ProcessId"), r("CommandLine"))
Next
End Sub
End Module
I think it could be easier if you set a Mutex when launching second app.
In main app you could do this: if Mutex doesn't exist you run second app (which creates Mutex when run and release it when closing), otherwise you skip...
EDITED:
You can't edit second app to insert the creation of a mutex, ok.
But you can do this in main app:
- Create a background worker
BackgroudWorker wrk
- Set a private bool to true:
bool running = false
- Execute wrk when you want the new app run:
if (running) return; running = true;
- wrk creates a Process and waits for its end
- when wrk ends
running = false
Just an idea...
EDITED AGAIN:
If you close first app and reopen it, user is able to run second app again.
So you could do this:
- Create a background worker
BackgroudWorker wrk
- Write a tmp file (on NTFS it can be empty)
- Execute wrk when you want the new app run:
if your tmp file exists then exit; - wrk creates a Process and waits for its end
- when wrk ends deletes tmp file
With this method, even if user quits your first app, tmp file remains on hdd; so when user runs first app again, second app will not be executed.
Remeber that if user is smart enough to undestand this, he could manully delete file and the trick is done.
Finally: are you sure user cannot run directly second app?
精彩评论