2015-07-28 56 views
-1

有沒有辦法檢測使用C#打印機的配置變化?檢測打印機配置更改

我在C#中通常睡線程,我想,當有在配置中的任何改變(如有人添加/刪除/更新打印機或有人更改默認打印機),它被通知。一旦收到通知,它將顯示簡單的消息。

這可能使用C#.NET或使用WMI?我已經經歷了可用的解決方案,但它們中沒有一個似乎適合我的要求。

+0

如果你寫的是什麼,你已經嘗試過的解決方案,以及爲什麼他們就像我說的不適合你的要求 – Nir

+1

,**我正在尋找一種方式來做到這一點你可能會得到更好的答案* *。我已經回顧了各種論壇提供的幫助,並且他們都沒有幫助解決我的目標,我還沒有實施。但對於信息,最接近我能達到爲[這裏](http://stackoverflow.com/questions/20529075/how-do-i-tell-when-the-default-printer-was-changed)。 – atp9

+0

從你鏈接到它的問題看起來像FindFirstPrinterChangeNotification與PRINTER_CHANGE_PRINTER將檢測到添加/刪除打印機和問題的答案告訴你如何檢測默認打印機改變 – Nir

回答

1

可以使用__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(); 
     } 
    } 
}