×

# C# 监听系统事件

hqy hqy 发表于2026-04-08 16:53:58 浏览5 评论0

抢沙发发表评论

# 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();}


打赏

本文链接:https://kinber.cn/post/6396.html 转载需授权!

分享到:


推荐本站淘宝优惠价购买喜欢的宝贝:

image.png

 您阅读本篇文章共花了: 

群贤毕至

访客