스캐너를 통한 바코드 입력 시, 정확성과 사용자 경험을 동시에 확보하기 위한 로직 설계가 중요하다. 주요 고려사항은 다음과 같다:
- 최신 유효 바코드만 반영해야 한다.
- 동일한 바코드가 반복되면 무시하고, 변경 시에만 업데이트한다.
- 입력된 바코드의 형식 및 검증이 필요하다.
- 누락 스캔을 감지해 사용자에게 경고하는 메커니즘이 포함되어야 한다.
전통적인 접근 방식은 두 가지로 나뉜다:
① 바코드 수신 후 즉시 텍스트 박스를 비우는 방식: 빠른 반응성을 제공하지만, 사용자가 스캔 성공 여부를 확인하기 어렵다.
② 바코드 수신 후 텍스트를 선택 상태로 유지하는 방식: 다음 입력 시 기존 내용이 자동으로 덮어씌워져 편리하지만, 실수로 이전 바코드를 재사용할 가능성이 있다.
최적의 설계는 이 두 방식의 장점을 결합하는 것이다. 예를 들어, 다음과 같은 구조를 적용할 수 있다:
- 애플리케이션 시작 시, 별도의 스레드에서 지속적으로 바코드 입력을 모니터링한다. 입력된 값을 텍스트 박스에 그대로 유지하면서, 포커스와 선택 상태를 관리하여 다음 입력을 쉽게 준비한다.
private string latestBarcode = "";
private string currentBarcode = "";
private void MonitorBarcodeInput()
{
while (true)
{
Thread.Sleep(5);
string inputText = txtBarcodeInput.Text;
if (IsValidBarcode(inputText))
{
currentBarcode = inputText;
if (currentBarcode != latestBarcode)
{
latestBarcode = currentBarcode; // 최신 값 저장
if (txtBarcodeInput.InvokeRequired)
{
BeginInvoke(new Action(() =>
{
txtBarcodeInput.Text = currentBarcode;
txtBarcodeInput.Focus();
txtBarcodeInput.SelectAll();
}));
}
else
{
txtBarcodeInput.Text = currentBarcode;
txtBarcodeInput.Focus();
txtBarcodeInput.SelectAll();
}
}
}
Thread.Sleep(1000); // 스캔 간격 조절
}
}
- 외부에서 현재 유효 바코드를 요청할 때는
GetActiveBarcode()메서드를 통해 안전하게 가져온다. 이후에는 입력 필드를 초기화하여 중복 스캔을 방지한다.
private string GetActiveBarcode()
{
string rawValue = txtBarcodeInput.Text;
return IsValidBarcode(rawValue) ? rawValue : "";
}
// 사용 예시
string scannedCode = GetActiveBarcode();
if (!string.IsNullOrEmpty(scannedCode))
{
// 처리 로직 수행
// 입력 필드 초기화
if (txtBarcodeInput.InvokeRequired)
{
BeginInvoke(new Action(() => txtBarcodeInput.Text = ""));
BeginInvoke(new Action(() => txtBarcodeInput.Focus()));
}
else
{
txtBarcodeInput.Text = "";
txtBarcodeInput.Focus();
}
}
이 설계는 실시간 반응성과 사용자 인식을 동시에 확보하며, 오류 발생 가능성을 줄이고 데이터 일관성을 유지한다. 특히 다중 스레드 환경에서 컨트롤 접근을 올바르게 처리하는 것이 핵심이다.