前言
打印管理和成本控制是企业信息化管理的重要组成部分。
帮助企业更有效地管理和监控打印费用,开发一款基于WinForm 的电脑打印计费软件。
该软件不仅提供了直观的用户界面和便捷的操作体验,还具备强大的功能模块,确保打印任务的高效处理和精确计费。
主要功能时时监控电脑端打印任务、打印纸张数,最后计算出打印费用;这次我们先实现打印任务监控。有兴趣的小伙伴们可以一起学习。
一、 效果展示
自助打印界面
打印文件监控
电脑打印服务
二、界面设计
vs 2022开发
三、代码实现
引用dll
using System.Management;
using System.Printing;
主要代码实现
string defPrintName = string.Empty;
List<PrintJob> listTemp = new List<PrintJob>();
public Form1()
{
InitializeComponent();
//获取电脑默认打印机名称
label1.Text = GetDefPrinterName();
//定时读取打印任务
System.Timers.Timer GetPrintTimer;
GetPrintTimer =
new System.Timers.Timer();
GetPrintTimer.Elapsed +=
new ElapsedEventHandler(GetPrintTimer_Elapsed);
GetPrintTimer.Enabled = true;
}
bool IsPrintTimerSkip = false;
//获取打印任务
void GetPrintTimer_Elapsed(object sender, ElapsedEventArgs e)
{
try
{
GetPrintList();
}
catch (Exception ex)
{
throw ex;
}
}
//获取操作系统默认打印机名称
public string GetDefPrinterName()
{
//获取所有打印机信息
string query = string
.Format("SELECT * from Win32_Printer ");
var searcher = new
ManagementObjectSearcher(query);
var printers = searcher.Get();
string strState = "";
foreach (var printer in printers)
{
if (bool.Parse(printer
.Properties["Default"].Value.ToString()) == true)
{
defPrintName = printer
.Properties["DeviceID"].Value.ToString();
}
}
return defPrintName;
}
//查询打印任务
public void GetPrintList()
{
if (IsPrintTimerSkip) return;
IsPrintTimerSkip = true;
var query2 =
"SELECT * FROM Win32_PrintJob";
using (var searcher2 =
new ManagementObjectSearcher(query2))
{
var collection =
searcher2.Get();
foreach (ManagementObject item in collection)
{
//暂停打印任务
PausePrintJob(item, true);
var model = listTemp.Where(a => a.Document ==
item.Properties["Document"].Value.ToString());
var count = model.Count();
PrintJob job =
new PrintJob();
if (count == 0)
{
try
{
job.Document =
(string)item.Properties["Document"].Value;
job.JobId =
Int32.Parse(item.Properties["JobId"].Value.ToString()).ToString();
job.PaperSize = item.Properties["PaperSize"].Value.ToString();
job.PagesPrinted =
Int32.Parse(item.Properties["PagesPrinted"].Value.ToString()).ToString();
job.TotalPages =
Int32.Parse(item.Properties["TotalPages"].Value.ToString()).ToString();
job.TimeSubmitted =
item.Properties["TimeSubmitted"].Value.ToString();
if (item
.Properties["JobStatus"].Value != null)
{
job.JobStatus =
item.Properties["JobStatus"].Value.ToString();
}
else
{
job.JobStatus = "";
}
job.StatusMask = "0";
listTemp.Add(job);
}
catch (Exception ex)
{
}
NewMethodLoadGrid();
}
else
{
model.FirstOrDefault().TotalPages =
item.Properties["TotalPages"].Value.ToString();
model.FirstOrDefault().PagesPrinted =
item.Properties["PagesPrinted"].Value.ToString();
model.FirstOrDefault().JobStatus =
item.Properties["JobStatus"].Value.ToString();
}
}
}
IsPrintTimerSkip = false;
}
绑定数据
//绑定数据
private void NewMethodLoadGrid()
{
if (listTemp != null && listTemp.Count > 0)
{
this.Invoke
(new EventHandler(delegate
{
dataGridView1.DataSource = null;
dataGridView1.DataSource = listTemp;
}));
}
}
实体对象
//实体对象
public class PrintJob
{
/// <summary>
/// 文件名称
/// </summary>
public string Document { get; set; }
/// <summary>
/// 打印序列
/// </summary>
public string JobId { get; set; }
/// <summary>
/// 打印机返回的状态中文描述字符串
/// </summary>
public string JobStatus { get; set; }
/// <summary>
/// 页面页码
/// </summary>
public string PaperSize { get; set; }
/// <summary>
/// 已打印页码
/// </summary>
public string PagesPrinted { get; set; }
/// <summary>
/// 总页数
/// </summary>
public string TotalPages { get; set; }
/// <summary>
/// 提交时间
/// </summary>
public string TimeSubmitted { get; set; }
/// <summary>
/// 状态
/// </summary>
public string StatusMask { get; set; }
}
暂停打印1
using System;
using System.Management;
public class PrintJobManager
{
/// <summary>
/// 暂停指定名称的打印作业。
/// </summary>
/// <param name="jobName">要暂停的打印作业名称(支持部分匹配)。</param>
/// <returns>是否成功执行了暂停操作。</returns>
public bool PausePrintJob(string jobName)
{
bool isActionPerformed = false;
try
{
// 构建查询字符串以查找符合名称条件的打印作业
string searchQuery = $"SELECT * FROM Win32_PrintJob WHERE Name LIKE '%{jobName}%'";
ManagementObjectSearcher searcher = new ManagementObjectSearcher(searchQuery);
ManagementObjectCollection printJobCollection = searcher.Get();
foreach (ManagementObject printJob in printJobCollection)
{
// 调用 "Pause" 方法暂停打印作业
printJob.InvokeMethod("Pause", null);
isActionPerformed = true;
}
}
catch (Exception ex)
{
// 记录异常信息(建议使用日志库)
Console.WriteLine($"Error pausing print job: {ex.Message}");
// 或者可以将异常信息记录到日志文件中
// Logger.LogError(ex);
}
return isActionPerformed;
}
}
暂停打印2
public bool PausePrintJob(ManagementObject currentPrintJob, bool makePause)
{
bool isActionPerformed = false;
try
{
// 检查 currentPrintJob 是否为空,避免空引用异常
if (currentPrintJob == null)
{
return isActionPerformed;
}
// 根据 makePause 参数决定暂停或恢复打印任务
if (makePause)
{
currentPrintJob.InvokeMethod("Pause", null);
isActionPerformed = true;
}
else
{
currentPrintJob.InvokeMethod("Resume", null);
isActionPerformed = true; // 修改为 true,表示操作已执行
}
}
catch (Exception ex)
{
// 处理异常(建议至少记录日志)
// 例如:Logger.LogError(ex);
Console.WriteLine($"Error in PausePrintJob: {ex.Message}");
}
return isActionPerformed;
}
打印控制
//打印控制
private void clearPrintAll(string action)
{
PrintServer localPrintServer = new LocalPrintServer();
PrintQueue pq = localPrintServer.GetPrintQueue("Microsoft Print To PDF");
pq.Refresh();
PrintJobInfoCollection allPrintJobs = pq.GetPrintJobInfoCollection();
foreach (PrintSystemJobInfo printJob in allPrintJobs)
{
switch (action)
{
case "Pause":
printJob.Pause();//暂停
listTemp.Last().JobStatus = "已暂停";
NewMethodLoadGrid();
break;
case "Cancel":
printJob.Cancel();//取消
listTemp.Last().JobStatus = "已取消";
NewMethodLoadGrid();
break;
case "Resume":
printJob.Resume();//恢复
listTemp.Last().JobStatus = "已完成";
listTemp.Last().StatusMask = "1";
NewMethodLoadGrid();
break;
}
}
}
基本操作
//暂停
private void button1_Click(object sender, EventArgs e)
{
clearPrintAll("Pause");
}
//取消
private void button2_Click(object sender, EventArgs e)
{
clearPrintAll("Cancel");
}
//恢复
private void button3_Click(object sender, EventArgs e)
{
clearPrintAll("Resume");
}
以上就是时时监控电脑上的打印任务,动手试试吧。
最后
如果你觉得这篇文章对你有帮助,不妨点个赞支持一下!你的支持是我继续分享知识的动力。如果有任何疑问或需要进一步的帮助,欢迎随时留言。
也可以加入微信公众号 [DotNet技术匠] 社区,与其他热爱技术的同行一起交流心得,共同成长!
优秀是一种习惯,欢迎大家留言学习!
作者:lindexi
出处:cnblogs.com/lindexi/p/18426258
声明:网络内容,仅供学习,尊重版权,侵权速删,歉意致谢!