Nota:
El acceso a esta página requiere autorización. Puede intentar iniciar sesión o cambiar directorios.
El acceso a esta página requiere autorización. Puede intentar cambiar los directorios.
Un objeto de servicio PosKeyboard lee las teclas de un teclado POS. Un teclado POS puede ser un teclado auxiliar o puede ser un teclado virtual que consta de algunas o todas las teclas del teclado del sistema. En Microsoft Point of Service para .NET (POS para .NET), la clase base de teclado POS es PosKeyboardBase.
Un objeto de servicio PosKeyboard sigue el modelo de dispositivo de entrada general:
- Cuando se recibe la entrada desde el teclado POS, se pone en cola un DataEvent.
- Si la propiedad AutoDisable es true, el dispositivo se deshabilita automáticamente cuando se pone en cola un evento DataEvent . Esto se realiza automáticamente mediante la clase PosKeyboardBase .
- Se entregará un evento DataEvent en cola a la aplicación cuando la propiedad DataEventEnabled esté true y se cumplan otros requisitos de entrega de eventos. La clase PosKeyboardBase administrará la entrega de eventos automáticamente.
- Se pone en cola un evento ErrorEvent si se produce un error al recopilar o procesar la entrada y se entrega a la aplicación cuando DataEventEnabled es true y se cumplen otros requisitos de entrega de eventos.
- La propiedad DataCount , que mantiene la clase PosKeyboardBase , puede leerse para obtener el número de eventos en cola.
- Todas las entradas en la cola se pueden eliminar mediante la llamada a ClearInput().
El teclado POS es un dispositivo de uso exclusivo:
- La aplicación debe reclamar el dispositivo antes de habilitarlo.
- La aplicación debe reclamar y habilitar el dispositivo antes de que el dispositivo comience a leer la entrada.
Esta sección contiene un objeto de servicio PosKeyboard de ejemplo que genera pulsaciones de tecla simuladas que se envían a la aplicación mediante DataEvents. Este ejemplo depende del objeto auxiliar de subprocesos presentado en Introducción a subprocesos lector de objetos de servicio. Para compilar este ejemplo, debe incluir el código de ese tema.
Para escribir un objeto de servicio
Agregue directivas using para Microsoft.PointofService, Microsoft.PointOfService.BaseServiceObjects y System.Threading.
Agregue el atributo global PosAssembly.
Elija un nombre de espacio de nombres adecuado para el proyecto.
Cree una clase service Object derivada de PosKeyboardBase.
Agregue el
ServiceObjectatributo a la clase Service Object mediante el valor DeviceType.PosKeyboard como tipo de dispositivo.
Para agregar características al objeto de servicio de teclado de ejemplo
Cree una clase auxiliar de subprocesos, KeyboardThreadingObject, derivada de ServiceObjectThreadHelper de la sección Subprocesos de lectura de objetos de servicio.
Implemente el método ServiceObjectThreadProcedure en la clase KeyboardThreadingObject . Este es el procedimiento que se ejecutará en un subproceso independiente. En el código de ejemplo siguiente, este método simula la entrada del teclado.
Esta clase de ejemplo implementa un método denominado SendKey y otro llamado ChangePowerState. Estos métodos son envolventes de elementos protegidos. Dado que están protegidos, no se pueden invocar directamente desde el objeto de subproceso.
Invalide el método PosCommon.Open para especificar las funcionalidades admitidas por este objeto de servicio y crear un nuevo objeto auxiliar de subprocesos.
Anule PosCommon.DeviceEnable específicamente para Abrir y Cerrar el asistente de subprocesos.
Implemente los métodos virtuales abstractos de PosCommon, lo que proporciona una funcionalidad mínima.
Ejecutar la aplicación
Este objeto de servicio de ejemplo se puede ejecutar junto con la aplicación de prueba proporcionada con el POS para el Kit de desarrollo de software (SDK) de .NET.
Para probar el objeto de servicio
Inicie la aplicación de prueba y seleccione SamplePosKeyboard en la lista desplegable Teclado .
Abra y reclame el dispositivo y seleccione el dispositivo con la casilla DeviceEnabled para habilitarlo.
Al activar el cuadro DataEventEnabled , el objeto de servicio enviará una única clave simulada a la aplicación. La clase PosKeyboardBase pone en cola dataEvent automáticamente cuando se llama a KeyDown.
Al seleccionar el cuadro Habilitar eventos de datos automáticamente , el objeto de servicio seguirá entregando caracteres, dos segundos de diferencia.
El objeto de servicio enviará pulsaciones de teclas simuladas para los caracteres desde 'a' hasta 'z'. Después, se enviará un evento StatusUpdateEvent que indique que el dispositivo está ahora sin conexión. La clase PosKeyboardBase envía automáticamente este evento cuando se cambia Properties.PowerState .
Example
En este ejemplo se muestra cómo desarrollar un objeto de servicio PosKeyboard simple. Admite un subproceso de lector independiente para enviar DataEvents de forma asincrónica a la aplicación. Una vez compilado, puede ejecutar el Objeto de Servicio junto con la aplicación de prueba incluida con el SDK de POS para .NET.
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using Microsoft.PointOfService;
using Microsoft.PointOfService.BaseServiceObjects;
[assembly: PosAssembly("Service Object Contractors, Inc.")]
namespace SOSamples.Keyboard
{
[ServiceObject(
DeviceType.PosKeyboard,
"SamplePosKeyboard",
"Sample PosKeyboard Service Object",
1,
9)]
public class SampleKeyboard : PosKeyboardBase
{
KeyboardThreadingObject ReadThread = null;
public SampleKeyboard()
{
// DevicePath must be set before Open() is called.
// In the case of Play and Plug hardware, the
// POS for .NET Base class will set this value.
DevicePath = "Sample Keyboard";
// NOTE: You can test the power notification events
// sent from this Service Object by selecting the
// "Power Notify" check box.
// Let the application know advanced power
// reporting is supported.
Properties.CapPowerReporting = PowerReporting.Advanced;
Properties.CapKeyUp = false;
}
~SampleKeyboard()
{
// Code added from previous sections to terminate
// the read thread started by the thread-helper
// object.
if (ReadThread != null)
{
ReadThread.CloseThread();
}
Dispose(false);
}
// Expose the protected KeyDown() method so that it can be
// called from our threading helper.
public void SendKey(int key)
{
KeyDown(key);
}
// Expose the protected PowerState property so it can be
// changed from the threading helper.
public void ChangePowerState(PowerState state)
{
Properties.PowerState = state;
}
#region Override Virtual PosCommon Members
public override void Open()
{
base.Open();
// Create the reader-thread object.
ReadThread = new KeyboardThreadingObject(this);
}
public override bool DeviceEnabled
{
get
{
return base.DeviceEnabled;
}
set
{
if (value != base.DeviceEnabled)
{
base.DeviceEnabled = value;
if (value == false)
{
// Stop the reader thread when the device
// is disabled.
ReadThread.CloseThread();
}
else
{
try
{
// By enabling the device, start the
// reader thread.
ReadThread.OpenThread();
}
catch (Exception e)
{
base.DeviceEnabled = false;
if (e is PosControlException)
throw;
throw new PosControlException(
"Unable to Enable Device",
ErrorCode.Failure, e);
}
}
}
}
}
#endregion Override Virtual PosCommon Members
#region Implement Abstract PosCommon Members
private string MyHealthText = "";
// PosCommon.CheckHealthText.
public override string CheckHealthText
{
get
{
// VerifyState(mustBeClaimed,
// mustBeEnabled).
VerifyState(false, false);
return MyHealthText;
}
}
// PosCommon.CheckHealth.
public override string CheckHealth(
HealthCheckLevel level)
{
// Verify that device is open, claimed and enabled.
VerifyState(true, true);
// Your code here:
// Check the health of the device and return a
// descriptive string.
// Cache result in the CheckHealthText property.
MyHealthText = "Ok";
return MyHealthText;
}
// PosCommon.DirectIOData.
public override DirectIOData DirectIO(
int command,
int data,
object obj)
{
// Verify that the device is open.
VerifyState(false, false);
return new DirectIOData(data, obj);
}
#endregion Implement Abstract PosCommon Members
}
#region Thread Helper Class
public class KeyboardThreadingObject :
ServiceObjectThreadHelper, IDisposable
{
// This is a helper class which will depend on
// being able to call back into the actual Service
// Object to pass along data. However, you cannot
// keep a strong reference to the Service Object,
// since that may prevent clean disposal, leaving
// hardware resources unavailable to other processes.
// Therefore, you create a weak reference. From this
// reference, you can get a temporary strong reference,
// which you can act on and then release.
WeakReference ServiceObjectReference;
// The name of the Service Object.
string ObjectName;
public KeyboardThreadingObject(SampleKeyboard so)
{
ObjectName = GetType().Name;
ServiceObjectReference = new WeakReference(so);
}
// This method will be called during initialization.
public override void ServiceObjectThreadOpen()
{
Logger.Info(ObjectName, "Keyboard Thread Open");
}
// This method will be called curing shutdown.
public override void ServiceObjectThreadClose()
{
Logger.Info(ObjectName, "Keyboard Thread Open");
}
// Your code used to monitor your device for input should
// go here. The implementation below generates simulated
// input as an example.
public override void ServiceObjectThreadProcedure(
AutoResetEvent ThreadStopEvent)
{
Logger.Info(ObjectName,
"Keyboard Thread Procedure Entered");
int KeyValue = (int)'a';
while (true)
{
// When this method is called by the
// ServiceObjectThreadHelper, it is obligated to
// exit when the event ThreadStopEvent has been
// set.
if (ThreadStopEvent.WaitOne(2000, false))
{
break;
}
if (KeyValue <= (int) 'z')
{
Logger.Info(ObjectName, "Reader Thread cycling");
// Try to get a strong reference to the Service
// Object using the weak reference saved when
// this helper object was created.
SampleKeyboard Keyboard =
ServiceObjectReference.Target
as SampleKeyboard;
// If this fails, that means the Service Object
// has already been disposed of - exit the thread.
if (Keyboard == null)
{
break;
}
if (Keyboard.DataEventEnabled == true)
{
// Call a method implemented in our Keyboard
// class to queue the key stroke.
Keyboard.SendKey(KeyValue);
// Simulate input by moving through the
// alphabet, sending one character at a time.
KeyValue++;
if (KeyValue >= (int)'z')
{
// Once you run out of input, simulate a
// power state change. Setting the SO's
// PowerState property to
// PowerState.Offline will cause a
// StatusUpdateEvent to be sent to the
// application.
Keyboard.ChangePowerState(
PowerState.Offline);
// Release the strong reference.
Keyboard = null;
// There is no more work, so exit the
// loop.
break;
}
}
// Release the strong reference.
Keyboard = null;
}
}
}
}
#endregion Thread Helper Class
}
Compilar el código
- Este ejemplo requiere que se incluya el código de la sección Introducción a los subprocesos del lector de objetos de servicio.
- Se debe hacer referencia a los ensamblados Microsoft.PointOfService y Microsoft.PointOfService.BaseServiceObjects .