这几天要开发一个程序,用USB二维码扫描器读取中文二文码。基本思路是用虚拟键盘的方式处理,但处理后发现,中文内容全部丢失。谁处理过此类问题。
代码如下
private int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam)
{ barCode.IsValid = false;
bool notChar = false;
if (nCode == 0)
{
EventMsg msg = (EventMsg)Marshal.PtrToStructure(lParam, typeof(EventMsg)); if (wParam == 0x100) //WM_KEYDOWN = 0x100
{
barCode.VirtKey = msg.message & 0xff; //虚拟码
barCode.ScanCode = msg.paramL & 0xff; //扫描码 StringBuilder strKeyName = new StringBuilder(255);
if (GetKeyNameText(barCode.ScanCode * 65536, strKeyName, 255) > 0)
{
barCode.KeyName = strKeyName.ToString().Trim(new char[] { ' ', '\0' });
}
else
{
barCode.KeyName = "";
} byte[] kbArray = new byte[256];
uint uKey = 0;
GetKeyboardState(kbArray);// 取得的按键状态中文全部丢失!!!
if (ToAscii(barCode.VirtKey, barCode.ScanCode, kbArray, ref uKey, 0))
{
barCode.AscII = uKey;
//Console.WriteLine(uKey);
barCode.Chr = Convert.ToChar(uKey);
}
else
{
notChar = true; //转到ascii字符失败,这不是一个正常字符,要去掉
}
if (DateTime.Now.Subtract(barCode.Time).TotalMilliseconds > 30) //30ms可以过滤掉连续按住一个键时的情况
{
if (notChar == false)
strBarCode = barCode.Chr.ToString();
else
strBarCode = "";
barCode.IsValid = false;
}
else
{
if (strBarCode.Length >= 5)
{
barCode.IsValid = true; //isValid为true表明这是个条码
}
if (notChar == false)
{
strBarCode += barCode.Chr.ToString();
}
barCode.BarCode = strBarCode;
} barCode.Time = DateTime.Now;
if (BarCodeEvent != null && barCode.IsValid) BarCodeEvent(barCode); //触发事件 }
}
return CallNextHookEx(hKeyboardHook, nCode, wParam, lParam);
}
代码如下
private int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam)
{ barCode.IsValid = false;
bool notChar = false;
if (nCode == 0)
{
EventMsg msg = (EventMsg)Marshal.PtrToStructure(lParam, typeof(EventMsg)); if (wParam == 0x100) //WM_KEYDOWN = 0x100
{
barCode.VirtKey = msg.message & 0xff; //虚拟码
barCode.ScanCode = msg.paramL & 0xff; //扫描码 StringBuilder strKeyName = new StringBuilder(255);
if (GetKeyNameText(barCode.ScanCode * 65536, strKeyName, 255) > 0)
{
barCode.KeyName = strKeyName.ToString().Trim(new char[] { ' ', '\0' });
}
else
{
barCode.KeyName = "";
} byte[] kbArray = new byte[256];
uint uKey = 0;
GetKeyboardState(kbArray);// 取得的按键状态中文全部丢失!!!
if (ToAscii(barCode.VirtKey, barCode.ScanCode, kbArray, ref uKey, 0))
{
barCode.AscII = uKey;
//Console.WriteLine(uKey);
barCode.Chr = Convert.ToChar(uKey);
}
else
{
notChar = true; //转到ascii字符失败,这不是一个正常字符,要去掉
}
if (DateTime.Now.Subtract(barCode.Time).TotalMilliseconds > 30) //30ms可以过滤掉连续按住一个键时的情况
{
if (notChar == false)
strBarCode = barCode.Chr.ToString();
else
strBarCode = "";
barCode.IsValid = false;
}
else
{
if (strBarCode.Length >= 5)
{
barCode.IsValid = true; //isValid为true表明这是个条码
}
if (notChar == false)
{
strBarCode += barCode.Chr.ToString();
}
barCode.BarCode = strBarCode;
} barCode.Time = DateTime.Now;
if (BarCodeEvent != null && barCode.IsValid) BarCodeEvent(barCode); //触发事件 }
}
return CallNextHookEx(hKeyboardHook, nCode, wParam, lParam);
}
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货