如何在C# WinForms应用中获取含GS分隔符的GS1 DataMatrix码
解决WinForms TextBox丢失GS(ASCII 29)分隔符的方案
方案1:修改TextBox的字符捕获逻辑
WinForms TextBox默认会过滤部分控制字符,可通过事件监听手动保留GS字符:
- 为TextBox绑定
KeyPress事件,直接捕获并保留ASCII 29字符:private void ScanTargetTextBox_KeyPress(object sender, KeyPressEventArgs e) { // 检测GS字符(ASCII 29) if (e.KeyChar == (char)29) { e.Handled = false; // 允许该字符被处理 ((TextBox)sender).Text += e.KeyChar; // 调整光标到文本末尾 ((TextBox)sender).SelectionStart = ((TextBox)sender).Text.Length; } }
方案2:全局监听窗体键盘输入
绕过TextBox的默认过滤逻辑,通过窗体的ProcessCmdKey方法捕获所有输入字符:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { const int WM_CHAR = 0x0102; if (msg.Msg == WM_CHAR) { char inputChar = (char)msg.WParam; // 捕获GS字符并添加到目标TextBox if (inputChar == (char)29) { ScanTargetTextBox.Text += inputChar; ScanTargetTextBox.SelectionStart = ScanTargetTextBox.Text.Length; return true; // 标记事件已处理,避免默认过滤 } } return base.ProcessCmdKey(ref msg, keyData); }
方案3:调整扫描器输出配置
确认NETUM C750的扫描设置,确保GS字符以原始ASCII码输出:
- 进入扫描器设置模式(参考设备手册),找到GS分隔符的输出选项,选择ASCII 29原始输出,而非功能键映射或可见字符替换。
- 验证扫描器的缓冲区配置,确认GS字符已被包含在输出序列中(与Notepad++可正常捕获的配置保持一致)。
方案4:使用自定义TextBox控件
若默认TextBox的过滤逻辑无法绕过,可创建自定义控件重写字符处理逻辑:
public class UnfilteredTextBox : TextBox { protected override void OnKeyPress(KeyPressEventArgs e) { // 允许所有字符输入,包括控制字符 e.Handled = false; base.OnKeyPress(e); } protected override void WndProc(ref Message m) { const int WM_CHAR = 0x0102; if (m.Msg == WM_CHAR) { char inputChar = (char)m.WParam; // 直接添加字符,跳过默认过滤 this.Text += inputChar; this.SelectionStart = this.Text.Length; m.Result = IntPtr.Zero; return; } base.WndProc(ref m); } }
验证方法
扫描完成后,可通过以下方式确认GS字符是否存在:
- 调用
Encoding.ASCII.GetBytes(ScanTargetTextBox.Text),检查返回的字节数组中是否包含0x1D。 - 直接将文本传入GS1解析器,验证应用标识符(AI)能否被正确识别提取。
内容的提问来源于stack exchange,提问作者Jean-marc Blanchet
相关产品推荐
相关产品推荐

