code

public delegate void ScanComplete(string text);
public class ScanFormBase : Form
    {
private Dictionary<TextBox, ScanComplete> tbHandler;
private Dictionary<TextBox, Control> nextFocus;
protected void registerScanControl(TextBox tb, ScanComplete handler, Control nextControl)
        {
            if (tb == null)
            {
                return;
            }

            tb.GotFocus += new EventHandler(tb_GotFocus);
            tb.KeyPress += new KeyPressEventHandler(tb_KeyPress);
            if (handler != null)
            {
                if (tbHandler == null)
                {
                    tbHandler = new Dictionary<TextBox, ScanComplete>();
                }
                tbHandler[tb] = handler;
            }

            if (nextControl != null)
            {
                if (nextFocus == null)
                {
                    nextFocus = new Dictionary<TextBox, Control>();
                }
                nextFocus[tb] = nextControl;
            }
        }
void tb_GotFocus(object sender, EventArgs e)
        {
            TextBox tb = sender as TextBox;
            if (tb != null)
            {
                //tb.SelectAll();
                var timer = new Timer { Interval = 100, Enabled = true };
                timer.Tick += (EventHandler)delegate
                {
                    tb.SelectAll();
                    timer.Dispose();
                };
            }
        }
void tb_KeyPress(object sender, KeyPressEventArgs e)
        {
            TextBox tb = sender as TextBox;
            if (tb == null)
            {
                return;
            }
            if (e.KeyChar == (char)Keys.Return)
            {
                if (tbHandler != null && tbHandler.ContainsKey(tb))
                {
                    tbHandler[tb](tb.Text);
                }
                if (nextFocus != null && nextFocus.ContainsKey(tb))
                {
                    nextFocus[tb].Focus();
                }
                e.Handled = true;
            }
        }
}

 

posted on 2019-08-08 14:43  邢帅杰  阅读(398)  评论(0编辑  收藏  举报