How to handle WndProc messages in WPF?

前端 未结 9 1172
不知归路
不知归路 2020-11-22 10:46

In Windows Forms, I\'d just override WndProc, and start handling messages as they came in.

Can someone show me an example of how to achieve the same thi

9条回答
  •  天涯浪人
    2020-11-22 11:15

    You can attach to the 'SystemEvents' class of the built-in Win32 class:

    using Microsoft.Win32;
    

    in a WPF window class:

    SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
    SystemEvents.SessionSwitch += SystemEvents_SessionSwitch;
    SystemEvents.SessionEnding += SystemEvents_SessionEnding;
    SystemEvents.SessionEnded += SystemEvents_SessionEnded;
    
    private async void SystemEvents_PowerModeChanged(object sender, PowerModeChangedEventArgs e)
    {
        await vm.PowerModeChanged(e.Mode);
    }
    
    private async void SystemEvents_PowerModeChanged(object sender, PowerModeChangedEventArgs e)
    {
        await vm.PowerModeChanged(e.Mode);
    }
    
    private async void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
    {
        await vm.SessionSwitch(e.Reason);
    }
    
    private async void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e)
    {
        if (e.Reason == SessionEndReasons.Logoff)
        {
            await vm.UserLogoff();
        }
    }
    
    private async void SystemEvents_SessionEnded(object sender, SessionEndedEventArgs e)
    {
        if (e.Reason == SessionEndReasons.Logoff)
        {
            await vm.UserLogoff();
        }
    }
    

提交回复
热议问题