Questions on KeyboardHook using c# winform

62 views Asked by At

When a barcode (code 128) is read with a barcode reader, I want it to be displayed as text in textbox1, and also the data corresponding to that barcode, retrieved from SQL Server (Let's call this program as a ProgramB).

Question: Before developing Program B, I came up with Program A beforehand, which uses a keyboard hook to display the barcode read by the reader as text in textbox1 and displays the next barcode in textbox1 when it reads another barcode. I have attached the relevant code below.

public partial class Form1 : Form
{
    // Low Level Keyboard Hook Callback Function
    private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);

    // Windows API Functions
    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern bool UnhookWindowsHookEx(IntPtr hhk);

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);

    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr GetModuleHandle(string lpModuleName);

    // Constants
    private const int WH_KEYBOARD_LL = 13;
    private const int WM_KEYDOWN = 0x0100;
    private string barcodeData = "";

    // Hook Handle
    private IntPtr hookHandle = IntPtr.Zero;

    // Hook Procedure
    private IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam)
    {
        if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
        {
            int vkCode = Marshal.ReadInt32(lParam);
            char key = (char)vkCode;
            if (key == '\r')
            {
                string cleanedBarcodeData = barcodeData.Replace(" ", "");
                textBox1.Invoke((MethodInvoker)delegate
                {
                    textBox1.Text = cleanedBarcodeData;
                    textBox1.SelectAll();
                });
                barcodeData = "";
            }
            else
            {
                barcodeData += key.ToString();
            }
        }
        return CallNextHookEx(hookHandle, nCode, wParam, lParam);
    }

    // Hook Install
    private void InstallHook()
    {
        LowLevelKeyboardProc proc = HookProc;
        IntPtr moduleHandle = GetModuleHandle(Process.GetCurrentProcess().MainModule.ModuleName);
        hookHandle = SetWindowsHookEx(WH_KEYBOARD_LL, proc, moduleHandle, 0);
    }

    // Hook Uninstall
    private void UninstallHook()
    {
        if (hookHandle != IntPtr.Zero)
        {
            UnhookWindowsHookEx(hookHandle);
            hookHandle = IntPtr.Zero;
        }
    }

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        this.ActiveControl = textBox1;
        InstallHook();
    }

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        UninstallHook();
    }

    private void textBox1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            textBox1.Text = barcodeData;
            barcodeData = "";
            textBox1.Focus();
        }
        else
        {
            barcodeData += e.KeyCode.ToString().Substring(1);
        }
    }
}

However, when I applied the same code to Program B, the results were different from the same basic configuration. In Program B, the text that appears in textbox1 immediately after reading the barcode with the barcode reader disappears almost immediately (in about 0.3 seconds…).

Additionally, when I scanned the barcode (code 128) 'Barcode-2222' with the barcode reader, the text 'BARCODE1/22222' appeared in Program A, while 'emMinus11111' appeared in Program B…

Why are different results obtained even though the same code is used?

0

There are 0 answers