// 條碼掃描器
// 窗體部分相關代碼
using System;
using System
using System
using System
using System
using System
using System
namespace ReadBadCode
{
public partial class frmTest : Form
{
BarCodeHook BarCode = new BarCodeHook();
public frmTest()
{
InitializeComponent();
BarCode
}
private delegate void ShowInfoDelegate(BarCodeHook
private void ShowInfo(BarCodeHook
{
if (this
{
this
}
else
{
textBox
textBox
textBox
textBox
textBox
textBox
}
}
void BarCode_BarCodeEvent(BarCodeHook
{
ShowInfo(barCode);
}
private void frmTest_Load(object sender
{
BarCode
}
private void frmTest_FormClosed(object sender
{
BarCode
}
private void textBox
{
if (textBox
{
MessageBox
}
}
}
}
BarCodeHook 類相關代碼
using System;
using System
using System
using System
using System
namespace ReadBadCode
{
public class BarCodeHook
{
public delegate void BarCodeDelegate(BarCodes barCode);
public event BarCodeDelegate BarCodeEvent;
public struct BarCodes
{
public int VirtKey; //虛擬碼
public int ScanCode; //掃描碼
public string KeyName; //鍵名
public uint AscII; //AscII
public char Chr; //字符
public string BarCode; //條碼信息
public bool IsValid; //條碼是否有效
public DateTime Time; //掃描時間
}
private struct EventMsg
{
public int message;
public int paramL;
public int paramH;
public int Time;
public int hwnd;
}
[DllImport(
private static extern int SetWindowsHookEx(int idHook
[DllImport(
private static extern bool UnhookWindowsHookEx(int idHook);
[DllImport(
private static extern int CallNextHookEx(int idHook
[DllImport(
private static extern int GetKeyNameText(int lParam
[DllImport(
private static extern int GetKeyboardState(byte[] pbKeyState);
[DllImport(
private static extern bool ToAscii(int VirtualKey
delegate int HookProc(int nCode
BarCodes barCode = new BarCodes();
int hKeyboardHook =
string strBarCode =
private int KeyboardHookProc(int nCode
{
if (nCode ==
{
EventMsg msg = (EventMsg)Marshal
if (wParam ==
{
barCode
barCode
StringBuilder strKeyName = new StringBuilder(
if (GetKeyNameText(barCode
{
barCode
}
else
{
barCode
}
byte[] kbArray = new byte[
uint uKey =
GetKeyboardState(kbArray);
if (ToAscii(barCode
{
barCode
barCode
}
if (DateTime
{
strBarCode = barCode
}
else
{
if ((ssage &
{
barCode
barCode
}
strBarCode += barCode
}
barCode
if (BarCodeEvent != null) BarCodeEvent(barCode); //觸發事件
barCode
}
}
return CallNextHookEx(hKeyboardHook
}
// 安裝鉤子
public bool Start()
{
if (hKeyboardHook ==
{
//WH_KEYBOARD_LL =
hKeyboardHook = SetWindowsHookEx(
}
return (hKeyboardHook !=
}
// 卸載鉤子
public bool Stop()
{
if (hKeyboardHook !=
{
return UnhookWindowsHookEx(hKeyboardHook);
}
return true;
}
}
From:http://tw.wingwit.com/Article/program/net/201311/12265.html