다음을 통해 공유


이벤트 처리기 샘플(.NET용 POS v1.14 SDK 설명서)

이 샘플에서는 애플리케이션이 Microsoft .NET용 POS(서비스 지점)에서 지원하는 5가지 이벤트 유형 중 어느 것에 대한 처리기를 등록할 수 있는지 보여 줍니다.

  • DataEvent
  • ErrorEvent
  • StatusUpdateEvent
  • OutputCompleteEvent
  • DirectIOEvent

또한 애플리케이션이 PosPrinter 디바이스에 대한 비동기 출력 요청을 관리하는 방법도 보여 줍니다.

샘플 프로젝트를 만들려면

  1. 비동기 출력 샘플에서 서비스 개체 샘플 코드를 컴파일하고 설치합니다.

  2. Microsoft Visual Studio 2013에서 Windows Forms 애플리케이션 프로젝트를 만듭니다.

  3. 아래 코드 섹션에는 두 파일 AsyncApp.csAsyncApp.Designer.cs가 포함되어 있습니다.

  4. 새로 만든 프로젝트에서 Form1.csAsyncApp.cs로 바꾸고 Form1.Designer.csAsyncApp.Designer.cs로 바꿉니다.

  5. 아직 없는 경우 Microsoft.PointOfService.dll에 대한 어셈블리 참조를 추가합니다. 표준 설치에서 이 파일은 Program Files (x86)\Microsoft Point Of Service\SDK에서 찾을 수 있습니다.

  6. 컴파일 및 실행

이 샘플을 실행하려면

  1. 이 샘플에서는 사용자가 비동기 출력 샘플 서비스 개체에 비동기 및 동기 인쇄 요청을 보낼 수 있는 GUI 사용자 인터페이스를 표시합니다.

  2. 서비스 개체는 동기 또는 비동기 여부에 관계없이 요청에서 반환되기 전에 몇 초 동안 대기합니다.

  3. UI는 텍스트 상자에 각 요청의 상태를 표시합니다.

이 샘플 코드는 다음과 같은 몇 가지 핵심 사항을 보여 줍니다.

  • OutputCompleteEvent 이벤트를 사용하여 서비스 개체가 출력 요청을 완료했음을 애플리케이션에 알립니다.
  • 리플렉션을 사용하여 이벤트 처리기를 등록합니다.
  • PosExplorer를 사용하여 특정 서비스 개체를 검색합니다.

리플렉션을 사용하여 지정된 개체에서 사용할 수 있는 이벤트를 검색하는 방법을 보여주기 위해 이 코드는 먼저 PosPrinter로 캐스팅하지 않고 CreateInstance(DeviceInfo)에서 반환된 PosCommon 개체를 사용합니다. 대부분의 경우 애플리케이션은 이러한 방식으로 제네릭일 필요가 없으므로 개체를 적절하게 캐스팅합니다.

// ASYNCAPP.CS
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Reflection;
using Microsoft.PointOfService;

namespace AsyncOutputApp
{
    public partial class AsyncApp : Form
    {
        PosCommon posCommon;
        PosExplorer posExplorer;

        public AsyncApp()
        {
            InitializeComponent();

            btnPrintAsync.Enabled = true;
            btnPrintSync.Enabled = true;

            posExplorer = new PosExplorer(this);
            posCommon = null;

            string SOName = "AsyncOutputPrinter";

            try
            {
                OpenDevice(SOName);
                SetupEvents();
            }
            catch
            {
                MessageBox.Show("The Service Object '" +
                        SOName + "' failed to load",
                        "Service Object Error",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Exclamation);

                btnPrintAsync.Enabled = false;
                btnPrintSync.Enabled = false;
            }
        }

        private void OpenDevice(string SOName)
        {
            string str = txtPrintResults.Text;
            DeviceInfo device = null;

            txtPrintResults.Clear();

            {
                // Retrieve the list of PosPrinter Service Objects.
                DeviceCollection devices =
                        posExplorer.GetDevices(
                        DeviceType.PosPrinter);

                // Iterate through the list looking for the one
                // needed for this sample.
                foreach(DeviceInfo d in devices)
                {
                    if(d.ServiceObjectName == SOName)
                    {
                        device = d;
                        break;
                    }
                }

                if (device == null)
                {
                    throw new Exception("Service Object not found");
                }

                txtPrintResults.Text = "Opening device: " +
                        device.ServiceObjectName + ", type: " +
                        device.Type + "\r\n";

                posCommon =
                        (PosCommon)posExplorer.CreateInstance(device);

                posCommon.Open();
                posCommon.Claim(0);
                posCommon.DeviceEnabled = true;
            }
        }

        // When this button is pressed, AsyncMode is turned off,
        // and the application waits for each print request
        // to complete before regaining control.
        private void btnPrintSync_Click(object sender, EventArgs e)
        {
            PosPrinter posPrinter = posCommon as PosPrinter;
            posPrinter.AsyncMode = false;

            txtPrintResults.AppendText(
                        "Printing will take place " +
                        "synchronously.\r\n");

            StartPrinting();
        }

        // When this button is pressed, AsyncMode is turned on. Print
        // requests will be queued and delivered on a
        // first-in-first-out basis.
        private void btnPrintAsync_Click(object sender, EventArgs e)
        {
            PosPrinter posPrinter = posCommon as PosPrinter;
            posPrinter.AsyncMode = true;

            txtPrintResults.AppendText(
                        "Printing will take place " +
                        "asynchronously.\r\n");

            StartPrinting();
        }

        private void StartPrinting()
        {
            PosPrinter posPrinter = posCommon as PosPrinter;

            txtPrintResults.AppendText(
                        "Calling PrintNormal to start " +
                        "printing...\r\n");

            // Notice that calling PrintNormal() here may not result
            // in a print request being sent immediately to the
            // printer. In asynchronous mode, the requested is
            // placed in a first-in-first-out queue managed by
            // POS for .NET.
            try
            {
                posPrinter.PrintNormal(
                            PrinterStation.Receipt,
                            "This is do-nothing print data");
            }
            catch (PosControlException e)
            {
                txtPrintResults.AppendText(
                            "PrintNormal threw a " +
                            "PosControlException! Description: " +
                            e.Message + "\r\n");

                return;
            }

            // When data is sent to an output device, POS for .NET
            // updates the OutputId property in the target object.
            // When an OutputCompleteEvent is sent to the app,
            // the OutputCompleteEventArgs will contain this id.
            Int32 id = posPrinter.OutputId;

            txtPrintResults.AppendText(
                        "PrintNormal has returned! OutputID = " +
                        id + "\r\n");
        }

        // Visual Studio-generated code.
        private void AsyncApp_Load(object sender, EventArgs e)
        {
        }

        #region Event Registration
        private void SetupEvents()
        {
            // All PosCommon objects support StatusUpdateEvent and
            // DirectIOEvent events, so simply register a handler
            // for those events.
            posCommon.StatusUpdateEvent +=
                        new StatusUpdateEventHandler(
                        co_OnStatusUpdateEvent);

            posCommon.DirectIOEvent +=
                        new DirectIOEventHandler(
                        co_OnDirectIOEvent);

            // In addition to the events common to all devices
            // (StatusUpdateEvent and DirectIOEvent), a device
            // type may also support DataEvent, ErrorEvent, or
            // OutputCompleteEvent events.
            //
            // In this example, the following code uses reflection
            // to determine which events are supported by this
            // object (posCommon).
            //
            // However, in the general case, an application will know
            // what type of device was returned when PosExplorer
            // CreateInstance() was called;therefore will not
            // need to use reflection, but can instead register
            // event handlers using the mechanism used for
            // StatusUpdateEvent and DirectIOEvent events above.
            EventInfo dataEvent =
                        posCommon.GetType().GetEvent(
                        "DataEvent");
            if (dataEvent != null)
            {
                dataEvent.AddEventHandler(posCommon,
                        new DataEventHandler(
                        co_OnDataEvent));

                txtPrintResults.AppendText("Registering Event: " +
                        "DataEvent\r\n");
            }

            EventInfo errorEvent =
                        posCommon.GetType().GetEvent(
                        "ErrorEvent");
            if (errorEvent != null)
            {
                errorEvent.AddEventHandler(posCommon,
                        new DeviceErrorEventHandler(
                        co_OnErrorEvent));

                txtPrintResults.AppendText("Registering Event: " +
                        "ErrorEvent\r\n");
            }

            EventInfo outputCompleteEvent =
                        posCommon.GetType().GetEvent(
                        "OutputCompleteEvent");
            if (outputCompleteEvent != null)
            {
                outputCompleteEvent.AddEventHandler(
                        posCommon, new OutputCompleteEventHandler(
                        co_OnOutputCompleteEvent));

                txtPrintResults.AppendText("Registering Event: " +
                        "OutputCompleteEvent\r\n");
            }
        }
        #endregion Event Registration

        #region Event Handlers
        private void co_OnDataEvent(
                        object obj,
                        DataEventArgs d)
        {
            txtPrintResults.AppendText(d.ToString() + "\r\n");
        }

        private void co_OnStatusUpdateEvent(
                        object source,
                        StatusUpdateEventArgs d)
        {
            txtPrintResults.AppendText(d.ToString() + "\r\n");
        }

        private void co_OnDirectIOEvent(
                        object source,
                        DirectIOEventArgs d)
        {
            txtPrintResults.AppendText(d.ToString() + "\r\n");
        }

        private void co_OnErrorEvent(
                        object source,
                        DeviceErrorEventArgs d)
        {
            string str = d.ToString();

            MessageBox.Show(d.ToString(),
                        "OnErrorEvent called",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Error);

            txtPrintResults.AppendText(d.ToString() + "\r\n");
        }

        private void co_OnOutputCompleteEvent(
                        object source,
                        OutputCompleteEventArgs d)
        {
            txtPrintResults.AppendText(d.ToString() + "\r\n");
        }
        #endregion Event Handlers
    }
}

// ASYNCAPP.DESIGNER.CS
namespace AsyncOutputApp
{
    partial class AsyncApp
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.txtPrintResults = new System.Windows.Forms.TextBox();
            this.btnPrintSync = new System.Windows.Forms.Button();
            this.btnPrintAsync = new System.Windows.Forms.Button();
            this.SuspendLayout();
            //
            // txtPrintResults
            //
            this.txtPrintResults.BackColor = System.Drawing.SystemColors.Window;
            this.txtPrintResults.Location = new System.Drawing.Point(12, 119);
            this.txtPrintResults.Multiline = true;
            this.txtPrintResults.Name = "txtPrintResults";
            this.txtPrintResults.ReadOnly = true;
            this.txtPrintResults.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
            this.txtPrintResults.Size = new System.Drawing.Size(650, 200);
            this.txtPrintResults.TabIndex = 3;
            //
            // btnPrintSync
            //
            this.btnPrintSync.Location = new System.Drawing.Point(12, 12);
            this.btnPrintSync.Name = "btnPrintSync";
            this.btnPrintSync.Size = new System.Drawing.Size(132, 39);
            this.btnPrintSync.TabIndex = 1;
            this.btnPrintSync.Text = "Print Synchronous";
            this.btnPrintSync.UseVisualStyleBackColor = true;
            this.btnPrintSync.Click += new System.EventHandler(this.btnPrintSync_Click);
            //
            // btnPrintAsync
            //
            this.btnPrintAsync.Location = new System.Drawing.Point(12, 57);
            this.btnPrintAsync.Name = "btnPrintAsync";
            this.btnPrintAsync.Size = new System.Drawing.Size(132, 39);
            this.btnPrintAsync.TabIndex = 2;
            this.btnPrintAsync.Text = "Print Asynchronously";
            this.btnPrintAsync.UseVisualStyleBackColor = true;
            this.btnPrintAsync.Click += new System.EventHandler(this.btnPrintAsync_Click);
            //
            // AsyncApp
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(685, 331);
            this.Controls.Add(this.btnPrintAsync);
            this.Controls.Add(this.btnPrintSync);
            this.Controls.Add(this.txtPrintResults);
            this.Name = "AsyncApp";
            this.Text = "Form1";
            this.Load += new System.EventHandler(this.AsyncApp_Load);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.TextBox txtPrintResults;
        private System.Windows.Forms.Button btnPrintSync;
        private System.Windows.Forms.Button btnPrintAsync;
    }
}

먼저 동기 인쇄 단추를 누른 다음 비동기 인쇄 단추를 누르면 프로그램에 다음 텍스트가 표시됩니다.

Opening device: AsyncOutputPrinter, type: PosPrinterRegistering Event: ErrorEventRegistering Event: OutputCompleteEventPrinting will take place synchronously.Calling PrintNormal to start printing...PrintNormal has returned! OutputID = 0Printing will take place asynchronously.Calling PrintNormal to start printing...PrintNormal has returned! OutputID = 1Microsoft.PointOfService.OutputCompleteEventArgs, TimeStamp: 11:35:39 AM, EventId: 1, OutputId: 1.

참고 항목

작업

개념

기타 리소스