开发者

Capturing windows event with java windows services

I want to capture lock/unlock/start/shutdown/log off and log on events through a windows service and then I want to fire a function for each event so that I can capture the time when Event occured.

I want to do this through a wind开发者_JAVA技巧ows service so that I need not run the program manually. And I want to run this program through java language.


Looks like you will need to use JNA and write the capture code with native Windows calls.

There is a class java.awt.Robot that does the reverse -- simulating OS events but I am not aware of the way to capture events in pure Java.


In C# it is pretty straightforward. I can show you code in C#, you can then convert it to Ja.Net if you want to use Java as a language. (if you actually want to use JVM, this won't help as much though).

  1. Create empty C# service.
  2. Inside your program Main method set CanHandleSessionChangeEvent property to true:

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    static void Main()
    {
        ServiceBase[] ServicesToRun;
        LogService logService = new LogService();
        logService.CanHandleSessionChangeEvent = true;
        ServicesToRun = new ServiceBase[] 
        { 
            logService 
        };
        ServiceBase.Run(ServicesToRun);
    }
    
  3. in service implementation override OnSessionChange event, where you can dump information on user logon/logoff and session connect/disconnect

    protected override void OnSessionChange(SessionChangeDescription changeDescription)
    {
        EventLog.WriteEvent(
            new EventInstance(100, 0, EventLogEntryType.Information), 
            String.Format("Reason: {0}, SessionId:{1}", changeDescription.Reason, changeDescription.SessionId));
        base.OnSessionChange(changeDescription);
    }
    
  4. Register service, start it up and see records in event log.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜