如何使用c#从Windows应用程序中的SessionSwitch
事件中调用方法?是否需要使用委托?请帮助您提供示例代码。
答案 0 :(得分:2)
像这样:
SystemEvents.SessionSwitch += HandleSessionSwitch;
...
private static void HandleSessionSwitch(object sender, Microsoft.Win32.SessionSwitchEventArgs e)
{
// do something
}
注意:当应用程序关闭或可能导致内存泄漏时,您应该取消订阅此事件(如documentation on MSDN中所述)。
答案 1 :(得分:1)
您必须处理Microsoft.Win32.SystemEvents.SessionSwitch
事件。请注意,处理程序方法必须是static
:
SystemEvents.SessionSwitch += new SessionSwitchEventHandler(SystemEvents_SessionSwitch);
[...]
static void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
{
// your code goes here
}
或者,一如既往,lambda表达式将执行:
SystemEvents.SessionSwitch += (sender, e) => { /* your code*/ };