0

I would you like popup a message box when the user print everything. The following code can done the job well:

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);
            }
        }
    }
}       

However, when I convert it to a windows services, it prompt the following error message:

An exception occurred while getting the default printer. Win32 error The system cannot find the file specified.

I would be grateful if any solution provided.

The KNVB
  • 3,588
  • 3
  • 29
  • 54

1 Answers1

0

Here is the workable code:

        try
        {
            WqlObjectQuery sql = new WqlObjectQuery("SELECT * FROM Win32_PrintJob");
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(sql);
            foreach (ManagementObject printJob in searcher.Get())
            {
                if (!prevJobName.Equals(printJob["Name"]))
                {
                    Console.WriteLine(printJob["Name"] + ":" + printJob["Status"]);
                    printJob.InvokeMethod("Pause", null);
                    prevJobName = (String)printJob["Name"];
                    Interop.ShowMessageBox("Click Ok To continue", "MyService Message");
                    printJob.InvokeMethod("Resume", null);
                }
            }
        }
        catch (Exception ex)
        {
            this.EventLog.WriteEntry(ex.ToString());
        }

Interop.cs source code (This object is used to popup message):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace PrintJobMonitor
{
    class Interop
    {
        public static IntPtr WTS_CURRENT_SERVER_HANDLE = IntPtr.Zero;
        public static void ShowMessageBox(string message, string title)
        {
            int resp = 0;
            WTSSendMessage(
                WTS_CURRENT_SERVER_HANDLE,
                WTSGetActiveConsoleSessionId(),
                title, title.Length,
                message, message.Length,
                0, 0, out resp, true);
        }

        [DllImport("kernel32.dll", SetLastError = true)]
        public static extern int WTSGetActiveConsoleSessionId();

        [DllImport("wtsapi32.dll", SetLastError = true)]
        public static extern bool WTSSendMessage(
            IntPtr hServer,
            int SessionId,
            String pTitle,
            int TitleLength,
            String pMessage,
            int MessageLength,
            int Style,
            int Timeout,
            out int pResponse,
            bool bWait);
    }
}

Reference Site(Chinese only)

The KNVB
  • 3,588
  • 3
  • 29
  • 54