Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Watching Global Events created by a native process in a .NET process

I have a global event created and set/reset in a native C++ process that are created like this:

HANDLE hGlobalEvent = CreateEvent(NULL, TRUE, FALSE, _T("Global\\MyEvent"));

Is there any way (even if it's with a library not written by MS) to register for one of these events in a .NET (C#) process so that I standard .NET events handlers are fired off when the global event changed?
And I don't really just want to wait on the event and loop, as is the way in C++ with WaitForSingleObject...I really would like it to be a completely asynchronous event handler.

I've got to imagine there's an easy way to do this...just can't find it.

like image 387
Adam Haile Avatar asked Sep 14 '25 14:09

Adam Haile


1 Answers

ThreadPool.RegisterWaitForSingleObject can be used to execute a callback when the event is signalled. Obtain a WaitHandle for the named event object by using the EventWaitHandle constructor that takes a string name.

bool createdNew;
WaitHandle waitHandle = new EventWaitHandle(false,
    EventResetMode.ManualReset, @"Global\MyEvent", out createdNew);
// createdNew should be 'false' because event already exists
ThreadPool.RegisterWaitForSingleObject(waitHandle, MyCallback, null,
    -1, true);

void MyCallback(object state, bool timedOut) { /* ... */ }
like image 90
Bradley Grainger Avatar answered Sep 17 '25 04:09

Bradley Grainger