LocalPrintServer.GetDefaultPrintQueue()在Windows服务中不起作用

时间:2016-08-11 01:48:52

标签: c# wmi wmi-query

当您打印所有内容时,我想要弹出一个消息框。 以下代码可以很好地完成工作:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Printing;
using System.Management;
using System.Windows.Forms;

namespace CatchByWMI
{
    class Program
    {
        static String prevJobName;
        static void Main(string[] args)
        {
            String strComputerName = "localhost";
            // Create event query to be notified within 1 second of 
            // a change in a service
            WqlEventQuery query = new WqlEventQuery("SELECT * FROM __InstanceOperationEvent WITHIN 0.1 WHERE TargetInstance ISA \"Win32_PrintJob\"");
            ManagementEventWatcher watcher = new ManagementEventWatcher();

            watcher.Scope = new ManagementScope("\\\\" + strComputerName + "\\root\\CIMV2");
            watcher.Query = query;

            // times out watcher.WaitForNextEvent in 5 seconds
            watcher.Options.Timeout = new TimeSpan(0, 0, 5);
            watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived);

            // Start listening
            watcher.Start();

            // Do something in the meantime
            System.Threading.Thread.Sleep(100000);

            // Stop listening
            watcher.Stop();
        }
        private static void watcher_EventArrived(object sender, EventArrivedEventArgs e)
        {
            try
            {
                PrintQueue printQueue = LocalPrintServer.GetDefaultPrintQueue();
                PrintJobInfoCollection coll = printQueue.GetPrintJobInfoCollection();

                String n = Environment.NewLine;

                foreach (PrintSystemJobInfo job in coll)
                {
                    if (!job.Name.Equals(prevJobName))
                    {
                        job.Pause();
                        Console.WriteLine(job.Name);
                        // MB_TOPMOST
                        MessageBox.Show("hello", "Header", MessageBoxButtons.OK, MessageBoxIcon.None, MessageBoxDefaultButton.Button1, (MessageBoxOptions)0x40000);
                        job.Resume();
                        prevJobName = job.Name;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}       

但是,当我将其转换为Windows服务时,它会提示以下错误消息:

获取默认打印机时发生异常。 Win32错误系统找不到指定的文件。

如果提供任何解决方案,我将不胜感激。

0 个答案:

没有答案