首页 > 编程语言 >C# 获取打印机队列的打印任务

C# 获取打印机队列的打印任务

时间:2023-04-20 13:56:15浏览次数:45  
标签:IntPtr 打印机 string C# CharSet 队列 int public out

 //引入命名空间:using System.Runtime.InteropServices;
        [DllImport("winspool.drv", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern bool SetDefaultPrinter(string printerName);

        [DllImport("winspool.drv", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern bool GetDefaultPrinter(StringBuilder pszBuffer, ref int pcchBuffer);

        [StructLayout(LayoutKind.Sequential)]
        public struct SYSTEMTIME
        {
            public short wYear;
            public short wMonth;
            public short wDayOfWeek;
            public short wDay;
            public short wHour;
            public short wMinute;
            public short wSecond;
            public short wMilliseconds;
        }

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        public struct JOB_INFO_1
        {
            public int JobId;
            public string pPrinterName;
            public string pMachineName;
            public string pUserName;
            public string pDocument;
            public string pDatatype;
            public string pStatus;
            public int Status;
            public int Priority;
            public int Position;
            public int TotalPages;
            public int PagesPrinted;
            public SYSTEMTIME Submitted;
        }

        [DllImport("winspool.drv", CharSet = CharSet.Auto)]
        public static extern bool OpenPrinter(string pPrinterName, out IntPtr phPrinter, IntPtr pDefault);

        [DllImport("winspool.drv", CharSet = CharSet.Auto)]
        public static extern bool ClosePrinter(IntPtr hPrinter);

        [DllImport("winspool.drv", CharSet = CharSet.Auto)]
        public static extern int EnumJobs(IntPtr hPrinter, int FirstJob, int NoJobs, int Level, IntPtr pInfo, int cdBuf,
                                          out int pcbNeeded, out int pcReturned);

        private static void peekPrinterJobs(string printerToPeek)
        {
            IntPtr handle;
            int FirstJob = 0;
            int NumJobs = 127;
            int pcbNeeded;
            int pcReturned;

            // open printer
            OpenPrinter(printerToPeek, out handle, IntPtr.Zero);

            // get num bytes required, here we assume the maxt job for the printer quest is 128 (0..127)
            EnumJobs(handle, FirstJob, NumJobs, 1, IntPtr.Zero, 0, out pcbNeeded, out pcReturned);

            // allocate unmanaged memory
            IntPtr pData = Marshal.AllocHGlobal(pcbNeeded);

            // get structs
            EnumJobs(handle, FirstJob, NumJobs, 1, pData, pcbNeeded, out pcbNeeded, out pcReturned);

            // create array of managed job structs
            JOB_INFO_1[] jobs = new JOB_INFO_1[pcReturned];

            // marshal struct to managed
            int pTemp = pData.ToInt32(); //start pointer
            for (int i = 0; i < pcReturned; ++i)
            {
                jobs[i] = (JOB_INFO_1)Marshal.PtrToStructure(new IntPtr(pTemp), typeof(JOB_INFO_1));
                pTemp += Marshal.SizeOf(typeof(JOB_INFO_1));
            }

            // cleanup unmanaged memory
            Marshal.FreeHGlobal(pData);

            // close printer
            ClosePrinter(handle);

            // printer jobs are in the jobs array now, do what you want to...
        }
        /// <summary>
        /// 获取默认打印机 
        /// </summary>
        /// <returns></returns>
        public static string GetDefaultPrinter()
        {
            const int ERROR_FILE_NOT_FOUND = 2;

            const int ERROR_INSUFFICIENT_BUFFER = 122;

            int pcchBuffer = 0;

            if (GetDefaultPrinter(null, ref pcchBuffer))
            {
                return "";
            }

            int lastWin32Error = Marshal.GetLastWin32Error();

            if (lastWin32Error == ERROR_INSUFFICIENT_BUFFER)
            {
                StringBuilder pszBuffer = new StringBuilder(pcchBuffer);
                if (GetDefaultPrinter(pszBuffer, ref pcchBuffer))
                {
                    return pszBuffer.ToString();
                }

                lastWin32Error = Marshal.GetLastWin32Error();
            }
            if (lastWin32Error == ERROR_FILE_NOT_FOUND)
            {
                return "";
            }
            return "";
        }

        /// <summary>
        /// 获取打印机的打印列表
        /// </summary>
        /// <param name="printName">打印机名称,本地</param>
        /// <returns>返回打印队列中文档名称字符串,多个之间用逗号连接</returns>
        public static string GetPrintJobs(string printName)
        {
            StringBuilder result = new StringBuilder();

            IntPtr handle;
            int FirstJob = 0;
            int NumJobs = 127;
            int pcbNeeded;
            int pcReturned;

            // open printer 
            OpenPrinter(printName, out handle, IntPtr.Zero);

            // get num bytes required, here we assume the maxt job for the printer quest is 128 (0..127) 
            EnumJobs(handle, FirstJob, NumJobs, 1, IntPtr.Zero, 0, out pcbNeeded, out pcReturned);

            // allocate unmanaged memory 
            IntPtr pData = Marshal.AllocHGlobal(pcbNeeded);

            // get structs 
            EnumJobs(handle, FirstJob, NumJobs, 1, pData, pcbNeeded, out pcbNeeded, out pcReturned);

            // create array of managed job structs 
            JOB_INFO_1[] jobs = new JOB_INFO_1[pcReturned];

            // marshal struct to managed 
            int pTemp = pData.ToInt32(); //start pointer 
            for (int i = 0; i < pcReturned; ++i)
            {
                jobs[i] = (JOB_INFO_1)Marshal.PtrToStructure(new IntPtr(pTemp), typeof(JOB_INFO_1));
                result.Append(jobs[i].pDocument);
                result.Append(",");
                pTemp += Marshal.SizeOf(typeof(JOB_INFO_1));
            }

            // cleanup unmanaged memory 
            Marshal.FreeHGlobal(pData);

            // close printer 
            ClosePrinter(handle);

            return result.ToString();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            string strJob = GetPrintJobs(textBox2.Text);
            strJob = string.IsNullOrWhiteSpace(strJob) ? "空" : strJob;
            textBox3.Text = textBox3.Text + strJob + "\r\n";
        }

 

标签:IntPtr,打印机,string,C#,CharSet,队列,int,public,out
From: https://www.cnblogs.com/handsomeziff/p/17336556.html

相关文章

  • 两种方式,轻松实现ChatGPT联网
    两种方式效果:方式一:浏览器搜索内嵌插件方式二:官方聊天页内嵌插件首先,要有一个谷歌浏览器,然后再安装一个叫ChatGPTforGoogle,直接在谷歌里搜一下就能找,也可以Chrome应用商店里搜索,找到直接安装就可以了。方式一:谷歌浏览器访问下面链接或者搜索:ChatGPTforGooglehttps://c......
  • Android之调用service的方法
    MainActivity.java:privateBackgroundMusicServicecaller;@OverrideprotectedvoidonCreate(BundlesavedInstanceState){Intentsvc=newIntent(getApplicationContext(),BackgroundMusicService.class);if(Build.VERSION.SDK_INT>=Build.VERSIO......
  • [Wechat]概念辨析:微信的生态平台/运管平台
    0引言微信的各类XX社区、XX文档、XX平台,实在是太多,让人眼花缭乱。必须得理一理了。1微信公众平台https://mp.weixin.qq.com/即微信公众号(小程序/订阅号/服务号)的管理平台微信公众平台是运营者通过微信公众号为微信用户提供资讯和服务的平台;而微信公众平台开......
  • 每个节点上的cadvisor采集数据后通过aggregate api将转换交给 metric-server
    metric-server主要用来通过aggregateapi向其它组件(kube-scheduler、HorizontalPodAutoscaler、Kubernetes集群客户端等)提供集群中的pod和node的cpu和memory的监控指标,弹性伸缩中的podautoscaler就是通过调用这个接口来查看pod的当前资源使用量来进行pod的扩缩容的。需要注意的是......
  • 01-CSS中的非布局样式
    title:01-CSS中的非布局样式publish:true前言CSS中,有很多非布局样式,这些样式(属性)和与布局无关,包括:字体、字重、颜色、大小、行高背景、边框滚动、换行装饰性属性(粗体、斜体、下划线)等。这篇文章,我们来对上面的部分样式做一个回顾。边框如何用边框画一个三角形?详见......
  • 02-CSS布局
    title:02-CSS布局publish:true前言常见的布局属性(1)display确定元素的显示类型:block:块级元素。inline:行内元素。inline-block:对外的表现是行内元素(不会独占一行),对内的表现是块级元素(可以设置宽高)。(2)position确定元素的位置:static:默认属性值。relative:......
  • CSS的一些小知识
    title:认识Web和Web标准publish:false隐藏盒子的几种方式隐藏盒子,有以下几种方式:(1)方式一:overflow:hidden;//隐藏盒子超出的部分(2)方式二:display:none; 隐藏盒子,而且不占位置(用的最多)比如,点击X,关闭京东首页上方的广告栏。(3)方式三:visibility:hidden;//隐......
  • CSS开发积累
    title:认识Web和Web标准publish:false让flex盒子中的子元素们,居中flex布局常用的三行代码:display:flex;justify-content:center;//子元素在横轴的对齐方式(左右居中)align-items:center;//子元素在竖轴的对齐方式(上下居中)让文字只显示一行,超出显示......
  • CSS文章推荐
    title:认识Web和Web标准publish:false2020-03-16Bootstrap中文文档:https://code.z01.com/v4/content/tables.html2020-03-13CSS实现鼠标悬停弹出微信二维码......
  • AtCoder Regular Contest 109 F 1D Kingdom Builder
    洛谷传送门AtCoder传送门考虑判断一个终止态是否可达。如果只有一个棋子连续段那一定可达;否则就存在\(\ge2\)个连续段。此时把放棋子看成删除,那么限制就是如果删除一个孤立的棋子(两边没有棋子)且还有别的格子有棋子,这个棋子的颜色异于其他连续段的两边棋子的颜色。设第一......