using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Permissions;
using Microsoft.Win32;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Collections;
using System.Threading;
using System.Security.AccessControl;
using System.Security.Principal;
using Microsoft.Win32.SafeHandles;
namespace EnumerateMutexACL
{
class Win
{
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern SafeWaitHandle OpenMutex(UInt32 desiredAccess, bool inheritHandle, string name);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool DuplicateHandle(IntPtr hSourceProcessHandle,
IntPtr hSourceHandle, IntPtr hTargetProcessHandle, out IntPtr lpTargetHandle,
uint dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, uint dwOptions);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CloseHandle(IntPtr hObject);
}
class Program
{
static void Main(string[] args)
{
const UInt32 MUTEX_ALL_ACCESS = 0x1F0001;
const uint DUPLICATE_CLOSE_SOURCE = 0x00000001;
Process proc = Process.GetProcessesByName("notepad")[0];
IntPtr p = proc.Handle;
SafeWaitHandle hMutex = Win.OpenMutex(MUTEX_ALL_ACCESS, false, "MSCTF.Asm.MutexDefault1");
IntPtr pp = hMutex.DangerousGetHandle();
IntPtr ppp = Process.GetCurrentProcess().Handle;
IntPtr pppp = IntPtr.Zero; // System.Diagnostics.Process.Start("calc").Handle;
Win.DuplicateHandle(p, pp, ppp, out pppp, MUTEX_ALL_ACCESS, false, DUPLICATE_CLOSE_SOURCE);
Win.CloseHandle(pppp);
if (Win.OpenMutex(MUTEX_ALL_ACCESS, false, "MSCTF.Asm.MutexDefault1").DangerousGetHandle() == IntPtr.Zero)
Console.Write("Success");
else
Console.Write("Failed");
Console.Read();
return;
}
}
}