笔记本充电状态有两种监测方式,一种是主动查询,另一种是注册充电状态变化事件
1,先说主动监控吧,建立一个线程,反复查询SystemInformation.PowerStatus.PowerLineStatus
- private void readPower()
- {
- while (true)
- {
- this.Invoke(new Action(() =>
- {
- if (SystemInformation.PowerStatus.PowerLineStatus == PowerLineStatus.Offline)
- {
- label1.Text = "断电状态!";
- SystemSounds.Beep.Play();
- }
- else if (SystemInformation.PowerStatus.PowerLineStatus == PowerLineStatus.Online)
- label1.Text = "插电状态";
- else if (SystemInformation.PowerStatus.PowerLineStatus == PowerLineStatus.Unknown)
- label1.Text = "未知状态";
- }));
-
-
- Thread.Sleep(1000);
- }
- }
第二种,用事件来接受充电状态变化
- // 创建WMI事件查询
- WqlEventQuery query = new WqlEventQuery("SELECT * FROM Win32_PowerManagementEvent");
- // 创建事件侦听器
- watcher = new ManagementEventWatcher(query);
- watcher.EventArrived += Watcher_EventArrived;
- // 启动事件监听
- watcher.Start();
- // 创建事件侦听器
- ManagementEventWatcher watcher = null;
- ///
- /// 只能知道是笔记本电源事件,无法知道是插电还是断电
- ///
- ///
- ///
- private void Watcher_EventArrived(object sender, EventArrivedEventArgs eventArgs)
- {
- // 设置事件处理程序
- PropertyData eventData = eventArgs.NewEvent.Properties["EventType"];
- if (eventData != null)
- {
- int eventType = Convert.ToInt32(eventData.Value);
-
- this.Invoke(new Action(() =>
- {
- label1.Text = eventType.ToString();
- }));
-
-
- if (eventType == 4)
- {
- Console.WriteLine("笔记本电源被拔出");
-
- // 在这里可以添加你想要执行的操作
- }
- else if (eventType == 5)
- {
- Console.WriteLine("笔记本电源已连接");
- // 在这里可以添加你想要执行的操作
- }
- }
- }
总结,第一种效果比第二种好,可以知道充电变化的结果是有电,还是断电,第二种只知道充电状态变化,但具体是什么变化,无法得知,状态值都是10,第一种唯一的不足,就是需要新建一个线程,比较消耗资源