C# print 打印任务窗口设置,新增搜索框,打印任务右击可重新打印

--MainForm.cs
 
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing.Printing;
using System.IO;
using System.Windows;
using Fleck;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Collections;
using log4net;
namespace printAPP
{
    public partial class MainForm : Form
    {
        private static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); 
        Print p = new Print();
        private ContextMenuStrip strip = new ContextMenuStrip();//新建选项菜单
       
        Boolean close = false;
        List<Dictionary<string, object>> searchList = new List<Dictionary<string, object>>();// 存储所有打印任务的内容
        int key = 0;//打印任务列表的主键
        public MainForm()
        {
            InitializeComponent();
            initListView();
            var allSockets = new List<IWebSocketConnection>();
            var server = new WebSocketServer("********");//链接地址
            ToolStripMenuItem tools = new ToolStripMenuItem("重新打印");
            tools.Click += new EventHandler(Search_Click);
            strip.Items.Add(tools); //添加带有"打印"的菜单
            server.Start(socket =>
            {
                socket.OnOpen = () =>
                {
                    allSockets.Add(socket);
                };
                socket.OnClose = () =>
                {
                    allSockets.Remove(socket);
                };
                socket.OnMessage = message =>
                {
                    updateListView(message);
                    allSockets.ToList().ForEach(s => s.Send("{code:'0000',msg:'接收成功'}"));
                };
            });
           
        }
        delegate void UpdateDelegate(string s);
        public void updateListView(String message)
        {
            if (TaskListView.InvokeRequired)
            {
                UpdateDelegate del = updateListView;
                TaskListView.Invoke(del, message);
            }
            else  // 如果不需要跨线程刷新,直接对treeView1操作
            {
                LogHelper.logerror.Error("接收打印数据:" + message);
                try {
                JArray ja = JArray.Parse(message);
                int index = 1;
                //(当然2,3代码的位置需要调整)然后,声明一个鼠标事件。
                this.TaskListView.MouseClick += new MouseEventHandler(listViewSearchMouseClick);
               
                foreach(JObject jo in ja){
                    jo.Add("printtime", "打印时间");
                    jo.Add("signexplain", "打印备注内容*******");
                    jo.Add("sign", "签收栏");
                    jo.Add("check", "已检视");
                    jo.Add("numberOfThis", index + "/" + ja.Count);
                    startPrint(jo);
                    this.TaskListView.BeginUpdate();  //数据更新,UI暂时挂起,直到EndUpdate绘制控件,可以有效避免闪烁并大大提高加载速度
                    ListViewItem lvi = new ListViewItem();
                    lvi.Text = ((JObject)jo)["orderNo"] + "";
                    lvi.SubItems.Add("打印");
                    lvi.SubItems.Add("已发送打印队列");
                    lvi.SubItems.Add(DateTime.Now.ToString());
                    //lvi.SubItems.Add("" + (++key));
                    lvi.Tag = "" + (++key);//隐藏列内容
                    this.TaskListView.Items.Add(lvi);
                    //存储任务列表的内容
                    Dictionary<string, object> hashMap = new Dictionary<string, object>();
                    ((JObject)jo)["isPreview"] = "true";//修改值,再次打印时先进入打印预览
                    hashMap.Add("jo", jo);
                    hashMap.Add("item", lvi);
                    searchList.Add(hashMap);
                    this.TaskListView.EndUpdate();  //结束数据处理,UI界面一次性绘制。
                    index++;
                }
             }catch(Exception e){
                 LogHelper.WriteLog(typeof(MainForm) + "类发生异常", e);
             }
           }
          
        }
        public void startPrint(Object obj)
        {
            if (((JObject)obj).Property("isPreview") != null && "true".Equals(((JObject)obj)["isPreview"] + ""))
            {
                p.CreatePrintPreview((JObject)obj);
            }
            else
            {
                p.CreatePrint((JObject)obj);
            }
           
        }
        public void initListView()
        {
            this.TaskListView.FullRowSelect = true;
            this.TaskListView.GridLines = true;
            this.TaskListView.View = System.Windows.Forms.View.Details;
            this.TaskListView.Columns.Add("**编码",800 / 4,HorizontalAlignment.Center);
            this.TaskListView.Columns.Add("打印类型", 800 / 4, HorizontalAlignment.Center);
            this.TaskListView.Columns.Add("任务状态", 800 / 4, HorizontalAlignment.Center);
            this.TaskListView.Columns.Add("下发时间", 800 / 4, HorizontalAlignment.Center);
            //this.TaskListView.Columns.Add("主键", 800 / 5, HorizontalAlignment.Center);
            this.TaskListView.Tag = "主键";//隐藏列
            // 初始化“查找”文本框
            if (this.textBox1.Text == "")
            {
                this.textBox1.Text = "订单编码";
                this.textBox1.ForeColor = Color.LightGray;
            }
            else
            {
                this.textBox1.ForeColor = Color.Black;
            }
        }
    
        private void notifyIcon_MouseDoubleClick(object sender, MouseEventArgs e) //双击最小化图标显示窗体
        {
            if (this.ShowInTaskbar == false)
            {
                notifyIcon.Visible = true;
                this.ShowInTaskbar = false;
                this.Show();
                this.Activate();
                this.WindowState = FormWindowState.Normal;
            }
        }
        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!close)
           {
                // 取消关闭窗体
                //e.Cancel = true;
                // 将窗体变为最小化
                //this.WindowState = FormWindowState.Minimized;
                //this.ShowInTaskbar = false; //不显示在系统任务栏
                //notifyIcon.Visible = true; //托盘图标可见
                close = true;
                Application.Exit();
            }
        }
        private void 打印机设置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PrintConfig printConfig=new PrintConfig();
            printConfig.ShowDialog();
        }
        // 自定义搜索按钮事件
        private void search_btn_Click(object sender, EventArgs e)
        {
            int index = 1;
            this.TaskListView.Items.Clear();//清空数据
            if ((this.textBox1.Text == null || this.textBox1.Text.Trim() == "") || (this.textBox1.Text == "订单编码" && this.textBox1.ForeColor == Color.LightGray))
            {
                foreach (Dictionary<string, object> map in searchList)
                {
                    ListViewItem lvi = (ListViewItem)map["item"];
                    this.TaskListView.BeginUpdate();  //数据更新,UI暂时挂起,直到EndUpdate绘制控件,可以有效避免闪烁并大大提高加载速度
                    this.TaskListView.Items.Add(lvi);
                    //strip.Items.Add("打印");//2
                    this.TaskListView.EndUpdate();  //结束数据处理,UI界面一次性绘制。
                    this.TaskListView.MouseClick += new MouseEventHandler(listViewSearchMouseClick);//鼠标事件
                    index++;
                }
            }
            else
            {
                foreach (Dictionary<string, object> map in searchList)
                {
                    ListViewItem lvi = (ListViewItem)map["item"];
                    string orderNo = lvi.Text;
                    if (orderNo != null && orderNo.Trim() != "" && orderNo.Trim().Contains(this.textBox1.Text))
                    {
                        this.TaskListView.BeginUpdate();  //数据更新,UI暂时挂起,直到EndUpdate绘制控件,可以有效避免闪烁并大大提高加载速度
                        this.TaskListView.Items.Add(lvi);
                        //strip.Items.Add("打印");//2
                        this.TaskListView.EndUpdate();  //结束数据处理,UI界面一次性绘制。
                        this.TaskListView.MouseClick += new MouseEventHandler(listViewSearchMouseClick);//鼠标事件
                        index++;
                    }
                }
            }
           
        }
        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
         {
             if (MessageBox.Show("真的要退出程序吗?", "退出程序", MessageBoxButtons.OKCancel) == DialogResult.OK)
             {
                 close = true;
                 Application.Exit();
             }
         }
        private void MainForm_Load(object sender, EventArgs e)
        {
        }
        private void MainForm_Shown(object sender, EventArgs e)
        {
            //更新 更新程序
            new CheckUpdate().ShowDialog();
        }
        private void listViewSearchMouseClick(object sender,MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)//鼠标右键按下时
            {
                strip.Show(this.TaskListView, e.Location);//弹出菜单
            }
        }
        private void Search_Click(object sender, EventArgs e)
        {
            ListViewItem foundItem = this.TaskListView.FindItemWithText(TaskListView.FocusedItem.SubItems[0].Text, true, 0);   //参数1:要查找的文本;参数2:是否子项也要查找;参数3:开始查找位置
            if (foundItem != null)
            {
                if (this.TaskListView.SelectedItems.Count > 1)
                {
                    this.TaskListView.SelectedItems[0].ForeColor = Color.Black;
                    this.TaskListView.SelectedItems[0].Selected = false;
                    MessageBox.Show("请选择一项进行打印!");
                    return;
                }
                //this.TaskListView.TopItem = foundItem; //定位到该项
                //foundItem.ForeColor = Color.Red;//选中后改为红色
                foundItem.Selected = true;
                string printNo = TaskListView.FocusedItem.Tag.ToString();//获取选中行的隐藏第5列的内容,即主键的内容
                // 遍历Dictionary<string, object>的数组
                foreach (Dictionary<string, object> map in searchList)
                {
                    ListViewItem lvi = (ListViewItem)map["item"];
                    string No = lvi.Tag.ToString();
                    if (No != null && No.Trim() != "" && No == printNo)
                    {
                        // 声明一个鼠标事件。
                        this.TaskListView.MouseClick += new MouseEventHandler(listViewSearchMouseClick);
                        startPrint(map["jo"]);
                        return;
                    }
                   
                }
               
            }
        }
        // “查询”文本框获取焦点事件
        private void textBox1_Enter(object sender, EventArgs e)
        {
            if (this.textBox1.Text == "**编码" && this.textBox1.ForeColor == Color.LightGray)
            {
                this.textBox1.Text = "";
            }
            this.textBox1.ForeColor = Color.Black;
        }
        // “查询”文本框失去焦点事件
        private void textBox1_Leave(object sender, EventArgs e)
        {
            if (this.textBox1.Text == "")
            {
                this.textBox1.Text = "**编码";
                this.textBox1.ForeColor = Color.LightGray;
            }
        }
       
        
    }
}
 
 
--MainForm.Desiner.cs
namespace printAPP
{
    partial class MainForm
    {
        /// <summary>
        /// 必需的设计器变量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;
        /// <summary>
        /// 清理所有正在使用的资源。
        /// </summary>
        /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }
        #region Windows 窗体设计器生成的代码
        /// <summary>
        /// 设计器支持所需的方法 - 不要
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
            this.TaskListView = new System.Windows.Forms.ListView();
            this.setting = new System.Windows.Forms.MenuStrip();
            this.打印机设置ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.退出ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.notifyIcon = new System.Windows.Forms.NotifyIcon(this.components);
            this.button1 = new System.Windows.Forms.Button();
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.setting.SuspendLayout();
            this.SuspendLayout();
            //
            // TaskListView
            //
            this.TaskListView.Location = new System.Drawing.Point(11, 27);
            this.TaskListView.Name = "TaskListView";
            this.TaskListView.Size = new System.Drawing.Size(773, 341);
            this.TaskListView.TabIndex = 5;
            this.TaskListView.UseCompatibleStateImageBehavior = false;
            //
            // setting
            //
            this.setting.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.打印机设置ToolStripMenuItem,
            this.退出ToolStripMenuItem});
            this.setting.Location = new System.Drawing.Point(0, 0);
            this.setting.Name = "setting";
            this.setting.Size = new System.Drawing.Size(784, 25);
            this.setting.TabIndex = 6;
            this.setting.Text = "menuStrip";
            //
            // 打印机设置ToolStripMenuItem
            //
            this.打印机设置ToolStripMenuItem.Name = "打印机设置ToolStripMenuItem";
            this.打印机设置ToolStripMenuItem.Size = new System.Drawing.Size(80, 21);
            this.打印机设置ToolStripMenuItem.Text = "打印机设置";
            this.打印机设置ToolStripMenuItem.Click += new System.EventHandler(this.打印机设置ToolStripMenuItem_Click);
            //
            // 退出ToolStripMenuItem
            //
            this.退出ToolStripMenuItem.Name = "退出ToolStripMenuItem";
            this.退出ToolStripMenuItem.Size = new System.Drawing.Size(44, 21);
            this.退出ToolStripMenuItem.Text = "退出";
            this.退出ToolStripMenuItem.Click += new System.EventHandler(this.退出ToolStripMenuItem_Click);
            //
            // notifyIcon
            //
            this.notifyIcon.Icon = ((System.Drawing.Icon)(resources.GetObject("notifyIcon.Icon")));
            this.notifyIcon.Text = "*******打印控件";
            this.notifyIcon.Visible = true;
            this.notifyIcon.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.notifyIcon_MouseDoubleClick);
            //
            // button1
            //
            this.button1.Location = new System.Drawing.Point(179, 374);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(56, 23);
            this.button1.TabIndex = 7;
            this.button1.Text = "查找";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.search_btn_Click);
            //
            // textBox1
            //
            this.textBox1.Location = new System.Drawing.Point(11, 376);
            this.textBox1.Name = "textBox1";
            this.textBox1.Size = new System.Drawing.Size(162, 21);
            this.textBox1.TabIndex = 8;
            this.textBox1.Enter += new System.EventHandler(this.textBox1_Enter);  //获得焦点事件
            this.textBox1.Leave += new System.EventHandler(this.textBox1_Leave);  //失去焦点事件。
            //
            // MainForm
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(784, 406);
            this.Controls.Add(this.textBox1);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.TaskListView);
            this.Controls.Add(this.setting);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.MaximizeBox = false;
            this.Name = "MainForm";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "********打印";
            this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.MainForm_FormClosing);
            this.Load += new System.EventHandler(this.MainForm_Load);
            this.Shown += new System.EventHandler(this.MainForm_Shown);
            this.setting.ResumeLayout(false);
            this.setting.PerformLayout();
            this.ResumeLayout(false);
            this.PerformLayout();
        }
       
        #endregion
        private System.Windows.Forms.ListView TaskListView;
        private System.Windows.Forms.MenuStrip setting;
        private System.Windows.Forms.ToolStripMenuItem 打印机设置ToolStripMenuItem;
        private System.Windows.Forms.ToolStripMenuItem 退出ToolStripMenuItem;
        private System.Windows.Forms.NotifyIcon notifyIcon;
        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.TextBox textBox1;
  

    }
}
 
posted @ 2018-07-31 16:13  军999  阅读(678)  评论(0)    收藏  举报