Search code examples
c#.netcomcom+

Receive SENS events in .NET


I want to receive SENS events when the screensaver goes on/off. My code is based on this article:

private static readonly string GUID = "{" + typeof(ScreensaverHandler).GUID.ToString() + "}";

[ComImport, Guid("4E14FBA2-2E22-11D1-9964-00C04FBBB345")]
private class EventSystem { }

[ComImport, Guid("7542E960-79C7-11D1-88F9-0080C7D771BF")]
private class EventSubcription { }

[ComImport, Guid("AB944620-79C6-11d1-88F9-0080C7D771BF")]
private class EventPublisher { }

[ComImport, Guid("cdbec9c0-7a68-11d1-88f9-0080c7d771bf")]
private class EventClass { }

public ScreensaverHandler() {
    IEventSystem es = (IEventSystem) new EventSystem();
    IEventSubscription sub = (IEventSubscription) new EventSubcription();
    sub.Description = "description";
    sub.SubscriptionName = "subscriptionname";
    sub.SubscriptionID = GUID;
    sub.InterfaceID = GetInterfaceGuid(typeof(SensEvents.ISensLogon));
    sub.SubscriberInterface = this; // implements SensEvents.ISensLogon 
    es.Store("EventSystem.EventSubscription", sub);
}

private static string GetInterfaceGuid(Type type) {
    object[] attributes = type.GetCustomAttributes(typeof(GuidAttribute), true);
    return "{" + ((GuidAttribute)attributes[0]).Value + "}";
}

The problem is that es.Store throws a System.UnauthorizedAccessException with Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))


Solution

  • You could be running into a side effect of this Microsoft security bulletin. You may need to loosen up the security restrictions on the event system dll.

    I would, if you are not already, first try this as admin. I just tested your code on Win Server 2008 as a full admin with no issues.

    Also, there is another very good article on the event system in .Net at CodeProject.