WePro2
WePro2

Reputation: 83

Close handle to a mutex in another process

I want to close a handle to a mutex located in another process, so I can run more than one instance of the application.

I already know this can be done, see Process Explorer. Example: Windows Minesweeper (Windows 7) uses a mutex to only allow one game, so I thought I would use it as an example since it's pre-installed with Windows and therefore easier for you guys to guide me.

The mutex that I need to close is \Sessions\1\BaseNamedObjects\Oberon_Minesweeper_Singleton, which I found using Process Explorer.

After closing this mutex I was able to launch two games of Minesweeper, but I want to do this in my program using C++.

After some searching I have found that I might need the API DuplicateHandle. So far I haven't been able to close the handle on this mutex.

Here is my code so far:

#include <Windows.h>
#include <iostream>

using namespace std;

void printerror(LPSTR location){
    printf("Error: %s_%d", location, GetLastError());
    cin.get();
}

int main(){
    DWORD pid = 0;
    HWND hMineWnd = FindWindow("Minesweeper", "Minesveiper");
    GetWindowThreadProcessId(hMineWnd, &pid);
    HANDLE hProc =OpenProcess(PROCESS_DUP_HANDLE, 0, pid);
    if(hProc == NULL){
        printerror("1");
        return 1;
    }
    HANDLE hMutex = OpenMutex(MUTEX_ALL_ACCESS, TRUE, "Oberon_Minesweeper_Singleton");
    if(hMutex == NULL){
        printerror("2");
        return 2;
    }
    if(DuplicateHandle(hProc, hMutex, NULL, 0, 0, FALSE, DUPLICATE_CLOSE_SOURCE) == 0){
        printerror("3");
        return 3;
    }
    if(CloseHandle(hMutex) == 0){
        printerror("4");
        return 4;
    }
    return 0;
}

This code returns 0, but the mutex is still there, and I am not able to launch more games of Minesweeper. I think some of my parameters to DuplicateHandle are wrong.

Upvotes: 1

Views: 5031

Answers (1)

DRH
DRH

Reputation: 8116

The second argument to DuplicateHandle expects "an open object handle that is valid in the context of the source process", however I believe the handle you're passing in would only be valid within the current process (OpenMutex creates a new handle to an existing mutex object). You'll likely need to determine what the mutex's handle is in the remote process, and use that value when calling DuplicateHandle.

Upvotes: 1

Related Questions