# C# 监听系统事件

事件

C#
SystemEvents.SessionSwitch += SystemEvents_SessionSwitch;
SystemEvents.SessionEnding += SystemEvents_SessionEnding;
SystemEvents.DisplaySettingsChanged += SystemEvents_DisplaySettingsChanged;

系统消息轮训

C#
[StructLayout(LayoutKind.Sequential)]
private struct MSG
        {
            public IntPtr hwnd;
            public uint message;
            public IntPtr wParam;
            public IntPtr lParam;
            public uint time;
            public POINT pt;
        }
[StructLayout(LayoutKind.Sequential)]
private struct POINT
        {
            public int X;
            public int Y;

            public POINT(int x, int y)
            {
                X = x;
                Y = y;
            }
        }
[DllImport("user32.dll")]
private static extern bool DispatchMessage([In] ref MSG lpmsg);
[DllImport("user32.dll")]
private static extern int GetMessage(out MSG lpMsg, IntPtr hWnd, uint wMsgFilterMin, uint wMsgFilterMax);

private Thread messageLoopThread;
private void MessageLoop()
{
    if (messageLoopThread is not null)
    {
        return;
    }
    messageLoopThread = new Thread(() =>
    {
        while (true)
        {
            try
            {
                while (GetMessage(out var msg, IntPtr.Zero, 0, 0) > 0)
                {
                    DispatchMessage(ref msg);
                }
            }
            catch (Exception ex)
            {
                Logger.Instance.Error(ex);
            }
        }
    });
    if (OperatingSystem.IsWindows())
    {
        messageLoopThread.SetApartmentState(ApartmentState.STA);
    }
    messageLoopThread.Start();
}