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


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

    1,先说主动监控吧,建立一个线程,反复查询SystemInformation.PowerStatus.PowerLineStatus

    1. private void readPower()
    2. {
    3. while (true)
    4. {
    5. this.Invoke(new Action(() =>
    6. {
    7. if (SystemInformation.PowerStatus.PowerLineStatus == PowerLineStatus.Offline)
    8. {
    9. label1.Text = "断电状态!";
    10. SystemSounds.Beep.Play();
    11. }
    12. else if (SystemInformation.PowerStatus.PowerLineStatus == PowerLineStatus.Online)
    13. label1.Text = "插电状态";
    14. else if (SystemInformation.PowerStatus.PowerLineStatus == PowerLineStatus.Unknown)
    15. label1.Text = "未知状态";
    16. }));
    17. Thread.Sleep(1000);
    18. }
    19. }

     第二种,用事件来接受充电状态变化

    1. // 创建WMI事件查询
    2. WqlEventQuery query = new WqlEventQuery("SELECT * FROM Win32_PowerManagementEvent");
    3. // 创建事件侦听器
    4. watcher = new ManagementEventWatcher(query);
    5. watcher.EventArrived += Watcher_EventArrived;
    6. // 启动事件监听
    7. watcher.Start();

    1. // 创建事件侦听器
    2. ManagementEventWatcher watcher = null;
    3. ///
    4. /// 只能知道是笔记本电源事件,无法知道是插电还是断电
    5. ///
    6. ///
    7. ///
    8. private void Watcher_EventArrived(object sender, EventArrivedEventArgs eventArgs)
    9. {
    10. // 设置事件处理程序
    11. PropertyData eventData = eventArgs.NewEvent.Properties["EventType"];
    12. if (eventData != null)
    13. {
    14. int eventType = Convert.ToInt32(eventData.Value);
    15. this.Invoke(new Action(() =>
    16. {
    17. label1.Text = eventType.ToString();
    18. }));
    19. if (eventType == 4)
    20. {
    21. Console.WriteLine("笔记本电源被拔出");
    22. // 在这里可以添加你想要执行的操作
    23. }
    24. else if (eventType == 5)
    25. {
    26. Console.WriteLine("笔记本电源已连接");
    27. // 在这里可以添加你想要执行的操作
    28. }
    29. }
    30. }

    总结,第一种效果比第二种好,可以知道充电变化的结果是有电,还是断电,第二种只知道充电状态变化,但具体是什么变化,无法得知,状态值都是10,第一种唯一的不足,就是需要新建一个线程,比较消耗资源

  • 相关阅读:
    维修电工实训装置
    【git】本地仓库与远程仓库如何建立连接
    Qtreeview改变当前节点的名称
    Swift Combine — Publisher、Operator、Subscriber概念介绍
    Netty系列(二):Netty拆包/沾包问题的解决方案
    聊聊分布式集群的基本概念
    网络安全学习:操作系统安装部署
    CSS--学习
    【图结构从入门到应用】图的表示和遍历,图搜索算法详解与示例
    『互联网架构』kafka集群搭建和使用
  • 原文地址:https://blog.csdn.net/u014194297/article/details/139635603