BarTender.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.ComponentModel;
  5. using System.Drawing;
  6. using System.Windows.Forms;
  7. using Seagull.BarTender.Print;
  8. using System.Data;
  9. using System.Runtime.InteropServices;
  10. namespace MES接口
  11. {
  12. public partial class BarTender : Form
  13. {
  14. #region Fields
  15. // Common strings.
  16. //format.BaseName 获取当前文件名,不包括后缀
  17. //format.Title 获取全部文件名,包括后缀
  18. //format.Status 文件是否被加载
  19. [DllImport("user32.dll")]
  20. public static extern bool ReleaseCapture();
  21. [DllImport("user32.dll")]
  22. public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
  23. public const int WM_SYSCOMMAND = 0x0112;
  24. public const int SC_MOVE = 0xF010;
  25. public const int HTCAPTION = 0x0002;
  26. private const string appName = "Label Print";
  27. private const string dataSourced = "Data Sourced";
  28. private Engine engine = null; // 新建打印机引擎
  29. private LabelFormatDocument format = null; // 当前打开的BTW文件对象
  30. private bool isClosing = false; // 正在关闭时此选项设置为true,会阻止缩略图加载.
  31. // 标签预览
  32. private string[] browsingFormats; // 当前选取的文件夹下的Btw文件
  33. Hashtable listItems; // A hash table containing ListViewItems and indexed by format name.
  34. // It keeps track of what formats have had their image loaded.
  35. Queue<int> generationQueue; // A queue containing indexes into browsingFormats
  36. // to facilitate the generation of thumbnails
  37. // 预览文件的索引
  38. int topIndex; // The top visible index in the lstLabelBrowser
  39. int selectedIndex; // 预览框选中文件的索引
  40. #endregion
  41. #region Enumerations
  42. // Indexes into our image list for the label browser.
  43. enum ImageIndex { LoadingFormatImage = 0, FailureToLoadFormatImage = 1 };
  44. #endregion
  45. #region Constructor
  46. /// <summary>
  47. /// 构造函数初始化
  48. /// </summary>
  49. public BarTender()
  50. {
  51. InitializeComponent();
  52. }
  53. #endregion
  54. #region Delegates
  55. delegate void DelegateShowMessageBox(string message);
  56. #endregion
  57. #region Event Handlers
  58. #region Form Event Handlers
  59. /// <summary>
  60. /// 页面启动的时候执行,和打印机进行连接
  61. /// </summary>
  62. /// <param name="sender"></param>
  63. /// <param name="e"></param>
  64. private void LabelPrint_Load(object sender, EventArgs e)
  65. {
  66. this.headBar1.MouseDown += new MouseEventHandler(this.headBar1_MouseDown);
  67. // 创建一个打印机进程
  68. try
  69. {
  70. engine = new Engine(true);
  71. }
  72. catch (PrintEngineException exception)
  73. {
  74. // 不能打印进程返回错误信息直接退出程序
  75. MessageBox.Show(this, exception.Message, appName);
  76. this.Close();
  77. return;
  78. }
  79. // 获取打印机列表
  80. Printers printers = new Printers();
  81. foreach (Printer printer in printers)
  82. {
  83. cboPrinters.Items.Add(printer.PrinterName);
  84. }
  85. if (printers.Count > 0)
  86. {
  87. // 设置下拉框选中默认打印机
  88. cboPrinters.SelectedItem = printers.Default.PrinterName;
  89. }
  90. // 设置预览框中的图标
  91. lstLabelBrowser.View = View.LargeIcon;
  92. lstLabelBrowser.LargeImageList = new ImageList();
  93. lstLabelBrowser.LargeImageList.ImageSize = new Size(100, 100);
  94. lstLabelBrowser.LargeImageList.Images.Add(Properties.Resources.LoadingFormat);
  95. lstLabelBrowser.LargeImageList.Images.Add(Properties.Resources.LoadingError);
  96. // 初始化一个队列
  97. listItems = new Hashtable();
  98. generationQueue = new Queue<int>();
  99. //设置打印份数的最大值
  100. txtIdenticalCopies.MaxLength = 9;
  101. txtSerializedCopies.MaxLength = 9;
  102. }
  103. /// <summary>
  104. /// 关闭窗口的时候执行该方法
  105. /// </summary>
  106. /// <param name="sender"></param>
  107. /// <param name="e"></param>
  108. private void LabelPrint_FormClosed(object sender, FormClosedEventArgs e)
  109. {
  110. isClosing = true;
  111. // 关闭窗口之前向后台请求取消尚未打印的内容
  112. thumbnailCacheWorker.CancelAsync();
  113. while (thumbnailCacheWorker.IsBusy)
  114. {
  115. Application.DoEvents();
  116. };
  117. // 如果已经启动了打印机,停止打印机并且不保存修改的文件SubString
  118. if (engine != null)
  119. engine.Stop(SaveOptions.DoNotSaveChanges);
  120. }
  121. /// <summary>
  122. ///打开文件夹的时候,选择该文件夹下面后缀名为.BTW的文件进行显示
  123. /// </summary>
  124. /// <param name="sender"></param>
  125. /// <param name="e"></param>
  126. private void btnOpen_Click(object sender, EventArgs e)
  127. {
  128. //选择文件的时提示的描述
  129. folderBrowserDialog.Description = "选择一个包含打印文件(*.BTW)的文件夹";
  130. DialogResult result = folderBrowserDialog.ShowDialog();
  131. if (result == DialogResult.OK)
  132. {
  133. lock (generationQueue)
  134. {
  135. generationQueue.Clear();
  136. }
  137. //清空之前选择的内容
  138. listItems.Clear();
  139. //将文件夹的路径赋值给TextBox
  140. txtFolderPath.Text = folderBrowserDialog.SelectedPath;
  141. //为选取的时候打印按钮为Disabled
  142. btnPrint.Enabled = false;
  143. //读取该文件夹下面的BTW文件,browsingFormats是文件名的字符串数组
  144. browsingFormats = System.IO.Directory.GetFiles(txtFolderPath.Text, "*.btw");
  145. // ListView序列化的长度
  146. lstLabelBrowser.VirtualListSize = browsingFormats.Length;
  147. }
  148. }
  149. /// <summary>
  150. /// 点击打印按钮的时候执行
  151. /// </summary>
  152. /// <param name="sender"></param>
  153. /// <param name="e"></param>
  154. private void btnPrint_Click(object sender, EventArgs e)
  155. {
  156. // 正在打印的时候锁定该进程
  157. // 用户点击也不展示SubString
  158. lock (engine)
  159. {
  160. bool success = true;
  161. // 设置打印参数
  162. if (format.PrintSetup.SupportsIdenticalCopies)
  163. {
  164. int copies = 1;
  165. success = Int32.TryParse(txtIdenticalCopies.Text, out copies) && (copies >= 1);
  166. if (!success)
  167. MessageBox.Show(this, "打印的份数必须大于1的整数", appName);
  168. else
  169. {
  170. format.PrintSetup.IdenticalCopiesOfLabel = copies;
  171. }
  172. }
  173. // 数据源是数据库的时候
  174. // Assign number of serialized copies if it is not datasourced.
  175. if (success && (format.PrintSetup.SupportsSerializedLabels))
  176. {
  177. int copies = 1;
  178. success = int.TryParse(txtSerializedCopies.Text, out copies) && (copies >= 1);
  179. if (!success)
  180. {
  181. MessageBox.Show(this, "打印份数必须是大于1的数字", appName);
  182. }
  183. else
  184. {
  185. format.PrintSetup.NumberOfSerializedLabels = copies;
  186. }
  187. }
  188. // 所有的验证条件通过执行打印
  189. if (success)
  190. {
  191. Cursor.Current = Cursors.WaitCursor;
  192. // 选择打印机的名称
  193. if (cboPrinters.SelectedItem != null)
  194. format.PrintSetup.PrinterName = cboPrinters.SelectedItem.ToString();
  195. //int waitForCompletionTimeout = 10000; // 10 seconds
  196. //Result result = format.Print(appName, waitForCompletionTimeout, out messages);
  197. //string messageString = "\n\nMessages:";
  198. //foreach (Seagull.BarTender.Print.Message message in messages)
  199. //{
  200. // messageString += "\n\n" + message.Text;
  201. //}
  202. //if (result == Result.Failure)
  203. // MessageBox.Show(this, "Print Failed" + messageString, appName);
  204. //else
  205. // MessageBox.Show(this, "Label was successfully sent to printer." + messageString, appName);
  206. }
  207. }
  208. }
  209. #endregion
  210. #region List View Event Handlers
  211. /// <summary>
  212. /// 选中预览文件的时候读取SubString
  213. /// </summary>
  214. /// <param name="sender"></param>
  215. /// <param name="e"></param>
  216. private void lstLabelBrowser_SelectedIndexChanged(object sender, EventArgs e)
  217. {
  218. if (lstLabelBrowser.SelectedIndices.Count == 1)
  219. {
  220. selectedIndex = lstLabelBrowser.SelectedIndices[0];
  221. EnableControls(false);
  222. picUpdatingFormat.Visible = true;
  223. // 启动后台加载函数读取内容
  224. // 读取到的数据显示在DataGridView当中
  225. BackgroundWorker formatLoader = new BackgroundWorker();
  226. formatLoader.DoWork += new DoWorkEventHandler(formatLoader_DoWork);
  227. formatLoader.RunWorkerCompleted += new RunWorkerCompletedEventHandler(formatLoader_RunWorkerCompleted);
  228. formatLoader.RunWorkerAsync(selectedIndex);
  229. }
  230. else if (lstLabelBrowser.SelectedIndices.Count == 0)
  231. {
  232. EnableControls(false);
  233. picUpdatingFormat.Visible = false;
  234. }
  235. }
  236. /// <summary>
  237. /// 读取完文件夹的时候展示问价在该区域
  238. /// </summary>
  239. /// <param name="sender"></param>
  240. /// <param name="e"></param>
  241. private void lstLabelBrowser_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
  242. {
  243. int btwFileIndex = e.ItemIndex;
  244. //如果不存在这个项目则设置成默认的图片
  245. if (listItems[browsingFormats[btwFileIndex]] == null)
  246. {
  247. e.Item = new ListViewItem(browsingFormats[btwFileIndex]);
  248. e.Item.ImageIndex = (int)ImageIndex.LoadingFormatImage;
  249. listItems.Add(browsingFormats[btwFileIndex], e.Item);
  250. }
  251. else
  252. {
  253. e.Item = (ListViewItem)listItems[browsingFormats[btwFileIndex]];
  254. }
  255. // 将索引添加到队列.
  256. if (e.Item.ImageIndex == (int)ImageIndex.LoadingFormatImage)
  257. {
  258. lock (generationQueue)
  259. {
  260. if (!generationQueue.Contains(btwFileIndex))
  261. generationQueue.Enqueue(btwFileIndex);
  262. }
  263. }
  264. // 将东西放进队列的时候,如果队列没有被占用则开始执行任务
  265. if (!thumbnailCacheWorker.IsBusy && (generationQueue.Count > 0))
  266. {
  267. thumbnailCacheWorker.RunWorkerAsync();
  268. }
  269. }
  270. /// <summary>
  271. /// 缓存读取的文件列表
  272. /// </summary>
  273. /// <param name="sender"></param>
  274. /// <param name="cacheEvent"></param>
  275. private void lstLabelBrowser_CacheVirtualItems(object sender, CacheVirtualItemsEventArgs cacheEvent)
  276. {
  277. topIndex = cacheEvent.StartIndex;
  278. lock (generationQueue)
  279. {
  280. for (int index = cacheEvent.StartIndex; index <= cacheEvent.EndIndex; ++index)
  281. {
  282. ListViewItem listViewItem = (ListViewItem)listItems[browsingFormats[index]];
  283. if ((listViewItem != null) && (listViewItem.ImageIndex == (int)ImageIndex.LoadingFormatImage))
  284. {
  285. if (!generationQueue.Contains(index))
  286. generationQueue.Enqueue(index);
  287. }
  288. }
  289. }
  290. // 任务资源可用的时候执行
  291. if (!thumbnailCacheWorker.IsBusy && (generationQueue.Count > 0))
  292. {
  293. thumbnailCacheWorker.RunWorkerAsync();
  294. }
  295. }
  296. #endregion
  297. #region Thumbnail Event Handlers
  298. /// <summary>
  299. /// Called when a thumbnail was loaded so it can be shown.
  300. /// </summary>
  301. /// <param name="sender"></param>
  302. /// <param name="e"></param>
  303. void thumbnailCacheWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
  304. {
  305. object[] args = e.UserState as object[];
  306. ListViewItem item = (ListViewItem)args[0];
  307. // 100 means we got the image successfully.
  308. if (e.ProgressPercentage == 100)
  309. {
  310. Image thumbnail = (Image)args[1];
  311. lstLabelBrowser.LargeImageList.Images.Add(item.Text, thumbnail);
  312. item.ImageIndex = lstLabelBrowser.LargeImageList.Images.IndexOfKey(item.Text);
  313. }
  314. else if (e.ProgressPercentage == 0) // 0 means we did not successfully get the format image.
  315. {
  316. item.ImageIndex = (int)ImageIndex.FailureToLoadFormatImage;
  317. }
  318. item.ListView.Invalidate(item.Bounds);
  319. }
  320. /// <summary>
  321. /// 后台启用函数加载缩略图
  322. /// </summary>
  323. /// <param name="sender"></param>
  324. /// <param name="e"></param>
  325. void thumbnailCacheWorker_DoWork(object sender, DoWorkEventArgs e)
  326. {
  327. BackgroundWorker worker = (BackgroundWorker)sender;
  328. int index;
  329. string fileName;
  330. // Loop until the queue of items that need to be loaded is empty or the worker was cancelled.
  331. while ((generationQueue.Count > 0) && !worker.CancellationPending && !isClosing)
  332. {
  333. lock (generationQueue)
  334. {
  335. // Get the index to use.
  336. index = generationQueue.Dequeue();
  337. }
  338. // If this is way out of our view don't bother generating it.
  339. if (Math.Abs(index - topIndex) < 30)
  340. {
  341. fileName = browsingFormats[index];
  342. // 检查文件是否出缩略图外都已经加载完成了
  343. ListViewItem item = (ListViewItem)listItems[fileName];
  344. if (item == null)
  345. {
  346. item = new ListViewItem(fileName);
  347. item.ImageIndex = (int)ImageIndex.LoadingFormatImage;
  348. listItems.Add(fileName, item);
  349. }
  350. // 没有缩略图的时候就给个默认的
  351. if (item.ImageIndex == (int)ImageIndex.LoadingFormatImage)
  352. {
  353. try
  354. {
  355. Console.WriteLine(fileName);
  356. Image btwImage = LabelFormatThumbnail.Create(fileName, Color.Gray, 100, 100);
  357. object[] progressReport = new object[] { item, btwImage };
  358. worker.ReportProgress(100, progressReport);
  359. }
  360. catch
  361. {
  362. object[] progressReport = new object[] { item, null };
  363. worker.ReportProgress(0, progressReport);
  364. }
  365. }
  366. }
  367. }
  368. }
  369. #endregion
  370. #region Format Loader Event Handlers
  371. /// <summary>
  372. ///在另一个进程中进行文件的读取,不用占用当前的界面
  373. /// </summary>
  374. /// <param name="sender"></param>
  375. /// <param name="e"></param>
  376. void formatLoader_DoWork(object sender, DoWorkEventArgs e)
  377. {
  378. int index = (int)e.Argument;
  379. string errorMessage = "";
  380. // 确保安全先锁定打印机,因为可能正在执行打印任务
  381. lock (engine)
  382. {
  383. //确保用户选中该列表
  384. if (selectedIndex == index)
  385. {
  386. try
  387. {
  388. if (format != null)
  389. //是否保存对文件的编辑
  390. format.Close(SaveOptions.SaveChanges);
  391. format = engine.Documents.Open(browsingFormats[index]);
  392. }
  393. catch (System.Runtime.InteropServices.COMException comException)
  394. {
  395. errorMessage = String.Format("Unable to open format: {0}\nReason: {1}", browsingFormats[index], comException.Message);
  396. format = null;
  397. }
  398. }
  399. }
  400. // 后台执行只能调用MessageBox来显示信息
  401. if (errorMessage.Length != 0)
  402. Invoke(new DelegateShowMessageBox(ShowMessageBox), errorMessage);
  403. }
  404. /// <summary>
  405. /// 文件加载完的时候执行
  406. /// 填充打印份数默认值为1,如果存在SubString则读取出来
  407. /// </summary>
  408. /// <param name="sender"></param>
  409. /// <param name="e"></param>
  410. void formatLoader_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
  411. {
  412. // 确保正在操作的时候不会丢失该文件
  413. lock (engine)
  414. {
  415. if (format != null)
  416. {
  417. EnableControls(true);
  418. cboPrinters.SelectedItem = format.PrintSetup.PrinterName;
  419. picUpdatingFormat.Visible = false;
  420. lblFormatError.Visible = false;
  421. //支持打印多份的时候
  422. if (format.PrintSetup.SupportsIdenticalCopies == false)
  423. {
  424. txtIdenticalCopies.Text = dataSourced;
  425. txtIdenticalCopies.ReadOnly = true;
  426. }
  427. else
  428. {
  429. txtIdenticalCopies.Text = format.PrintSetup.IdenticalCopiesOfLabel.ToString();
  430. txtIdenticalCopies.ReadOnly = false;
  431. }
  432. //数据源是数据库的时候
  433. if (format.PrintSetup.SupportsSerializedLabels == false)
  434. {
  435. txtSerializedCopies.Text = dataSourced;
  436. txtSerializedCopies.ReadOnly = true;
  437. }
  438. else
  439. {
  440. txtSerializedCopies.Text = format.PrintSetup.NumberOfSerializedLabels.ToString();
  441. txtSerializedCopies.ReadOnly = false;
  442. }
  443. //DataTable dt = new DataTable();
  444. //DataRow row = dt.NewRow();
  445. //dt.Columns.Add(new DataColumn("name"));
  446. //dt.Columns.Add(new DataColumn("sex"));
  447. //dt.Columns.Add(new DataColumn("age"));
  448. //row["name"] = "John";
  449. //row["sex"] = "Smith";
  450. //row["age"] = "18";
  451. //dt.Rows.Add(row);
  452. //MessageBox.Show(format.SubStrings[0].Name);
  453. //获取具名数据源
  454. if (format.SubStrings.Count > 0){
  455. BindingSource bindingSource = new BindingSource();
  456. bindingSource.DataSource = format.SubStrings;
  457. substringGrid.DataSource = bindingSource;
  458. substringGrid.AutoResizeColumns();
  459. lblNoSubstrings.Visible = false;
  460. }else{
  461. lblNoSubstrings.Visible = true;
  462. }
  463. substringGrid.Invalidate();
  464. }
  465. else // 没有文件的时候,隐藏标签信息
  466. {
  467. picUpdatingFormat.Visible = false;
  468. lblNoSubstrings.Visible = false;
  469. lblFormatError.Visible = true;
  470. }
  471. }
  472. }
  473. #endregion
  474. #endregion
  475. #region Methods
  476. /// <summary>
  477. ///打开的文件无效禁用所有的控件
  478. /// </summary>
  479. /// <param name="enable"></param>
  480. void EnableControls(bool enable)
  481. {
  482. txtIdenticalCopies.Enabled = enable;
  483. txtSerializedCopies.Enabled = enable;
  484. btnPrint.Enabled = enable;
  485. if (!enable)
  486. {
  487. txtIdenticalCopies.Text = "";
  488. txtSerializedCopies.Text = "";
  489. substringGrid.DataSource = null;
  490. lblFormatError.Visible = false;
  491. lblNoSubstrings.Visible = false;
  492. }
  493. }
  494. /// <summary>
  495. /// 重写一个展示消息的方法
  496. /// </summary>
  497. /// <param name="message">展示的信息</param>
  498. void ShowMessageBox(string message)
  499. {
  500. MessageBox.Show(this, message, appName);
  501. }
  502. #endregion
  503. private void headBar1_MouseDown(object sender, MouseEventArgs e)
  504. {
  505. ReleaseCapture();
  506. SendMessage(this.Handle, WM_SYSCOMMAND, SC_MOVE + HTCAPTION, 0);
  507. }
  508. }
  509. }