检测c#中的打印机配置更改

本文关键字:配置 打印机 检测 | 更新日期: 2023-09-27 18:05:03

是否有一种方法可以使用c#检测打印机的配置更改?

我在c#中有一个线程,它通常会休眠,我希望它在配置发生任何变化时得到通知(比如有人添加/删除/更新打印机或有人更改默认打印机)。一旦收到通知,它将显示简单的消息。

是否可以使用c#。. NET还是使用WMI?我已经浏览了可用的解决方案,但似乎没有一个适合我的需求。

检测c#中的打印机配置更改

您可以使用__InstanceModificationEvent事件和Win32_Printer WMI类监视打印机配置更改

试试这个例子。

using System;
using System.Collections.Generic;
using System.Management;
using System.Text;

namespace GetWMI_Info
{
    public class EventWatcherAsync
    {
        private void WmiEventHandler(object sender, EventArrivedEventArgs e)
        {
            Console.WriteLine("TargetInstance.Name :       " + ((ManagementBaseObject)e.NewEvent.Properties["TargetInstance"].Value)["Name"]);
        }
        public EventWatcherAsync()
        {
            try
            {
                string ComputerName = "localhost";
                string WmiQuery;
                ManagementEventWatcher Watcher;
                ManagementScope Scope;

                if (!ComputerName.Equals("localhost", StringComparison.OrdinalIgnoreCase))
                {
                    ConnectionOptions Conn = new ConnectionOptions();
                    Conn.Username = "";
                    Conn.Password = "";
                    Conn.Authority = "ntlmdomain:DOMAIN";
                    Scope = new ManagementScope(String.Format("''''{0}''root''CIMV2", ComputerName), Conn);
                }
                else
                    Scope = new ManagementScope(String.Format("''''{0}''root''CIMV2", ComputerName), null);
                Scope.Connect();
                WmiQuery = "Select * From __InstanceModificationEvent Within 1 " +
                "Where TargetInstance ISA 'Win32_Printer' ";
                Watcher = new ManagementEventWatcher(Scope, new EventQuery(WmiQuery));
                Watcher.EventArrived += new EventArrivedEventHandler(this.WmiEventHandler);
                Watcher.Start();
                Console.Read();
                Watcher.Stop();
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception {0} Trace {1}", e.Message, e.StackTrace);
            }
        }
        public static void Main(string[] args)
        {
            Console.WriteLine("Listening {0}", "__InstanceModificationEvent");
            Console.WriteLine("Press Enter to exit");
            EventWatcherAsync eventWatcher = new EventWatcherAsync();
            Console.Read();
        }
    }
}