2010年11月1日 星期一

C# Handle Windows Event (Send and Receive)

Using C# to handle windows event, we have to declare some extern methods first.

[DllImport("Kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern IntPtr OpenEvent(UInt32 dwDesiredAccess,
bool bInheritHandle, String lpName);

[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern IntPtr CreateEvent(IntPtr lpEventAttributes,
bool bManualReset, bool bInitialState, string lpName);

[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CloseHandle(IntPtr hObject);

[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool SetEvent(IntPtr hEvent);

For Sending event, use "CreateEvent", "SetEvent" and "CloseHandle".
For Receiving event, use "OpenEvent".

  • Send Event


  • // You could put CreateEvent in the contructor
    IntPtr evtHandle = CreateEvent(IntPtr.Zero, false, false, "CUSTOM_EVENT_NAME");

    // Each time you need to send the event, just call SetEvent.
    SetEvent(evtHandle);

    // Put this in the de-constructor(~Constructor) to close this handle.
    CloseHandle(evtHandle);

  • Receive Event


  • IntPtr evt;
    while (true)
    {
    if (OpenEvent(out evt))
    {
    AutoResetEvent arEvt = new AutoResetEvent(false);
    arEvt.SafeWaitHandle = new Microsoft.Win32.SafeHandles.SafeWaitHandle(evt, true);
    WaitHandle[] waitHandles = new WaitHandle[] { arEvt };
    while (true)
    {
    int waitResult = WaitHandle.WaitAny(waitHandles, 500, false);
    if (waitResult == 0)
    {
    //Do something
    }
    }
    }
    Thread.Sleep(2000);
    }


    private static bool OpenEvent(out IntPtr evt)
    {
    uint unEventPermissions = 2031619;
    // Same as EVENT_ALL_ACCESS value in the Win32 realm
    evt = OpenEvent(unEventPermissions, false, "CUSTOM_EVENT_NAME");
    if (evt == IntPtr.Zero)
    return false;
    else
    return true;
    }