欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 建筑 > 用winform开发一个笔记本电脑是否在充电的小工具

用winform开发一个笔记本电脑是否在充电的小工具

2025/4/29 8:23:01 来源:https://blog.csdn.net/u014194297/article/details/139635603  浏览:    关键词:用winform开发一个笔记本电脑是否在充电的小工具

 笔记本充电状态有两种监测方式,一种是主动查询,另一种是注册充电状态变化事件

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; 
/// <summary>/// 只能知道是笔记本电源事件,无法知道是插电还是断电/// </summary>/// <param name="sender"></param>/// <param name="eventArgs"></param>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,第一种唯一的不足,就是需要新建一个线程,比较消耗资源

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词