注册消息,获取电源事件
下面为获取开合盖动作的例子,如需其他电源事件消息,更换GUID_CONSOLE_DISPLAY_STATUS 的GUID即可,链接在最后面。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using testapp.NewFolder1;
using WpfControlLibrary1;
namespace testapp
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window, INotifyPropertyChanged
{
## **//GUID_CONSOLE_DISPLAY_STATUS 需要根据获取消息的不同而不同**
public static Guid GUID_CONSOLE_DISPLAY_STATUS = new Guid("BA3E0F4D-B817-4094-A2D1-D56379E6A0F3");
[DllImport(@"User32", SetLastError = true, EntryPoint = "RegisterPowerSettingNotification", CallingConvention = CallingConvention.StdCall)]
public static extern IntPtr RegisterPowerSettingNotification(IntPtr hRecipient, ref Guid PowerSettingGuid, Int32 Flags);
public MainWindow()
{
InitializeComponent();
}
protected override void OnSourceInitialized(EventArgs e)
{
base.OnSourceInitialized(e);
HwndSource source = PresentationSource.FromVisual(this) as HwndSource;
source.AddHook(WndProc);
RegisterPowerSettingNotification(source.Handle, ref GUID_CONSOLE_DISPLAY_STATUS, 0);//注册电源事件获取开关盖动作等
}
private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
switch (msg)
{
case 0x0218: //WM_POWERBROADCAST
if (wParam != IntPtr.Zero)
{
switch (wParam.ToInt32())
{
case 0x8013 : //PBT_POWERSETTINGCHANGE
if (lParam != null)
{
POWERBROADCAST_SETTING ps = (POWERBROADCAST_SETTING)Marshal.PtrToStructure(lParam, typeof(POWERBROADCAST_SETTING));
if (ps.GUID == GUID_CONSOLE_DISPLAY_STATUS)
{
if (ps.Data.ToString() == "0")//合盖
{
MessageBox.Show("1");
}
if (ps.Data.ToString() == "1")//开盖
{
}
}
}
break;
}
}
break;
}
return IntPtr.Zero;
}
public struct POWERBROADCAST_SETTING
{
public Guid GUID;
public int DataLength;
public byte Data;
}
}
}
上文中的GUID_CONSOLE_DISPLAY_STATUS 根据所要获取消息滴不同而不同。
具体解锁如下链接:
https://docs.microsoft.com/en-us/windows/win32/power/power-setting-guids