如何在Windows应用程序中制作键盘

时间:2016-09-09 07:14:54

标签: c# winforms keyboard .net-3.5

我在使用

的Windows窗体应用程序中需要键盘功能
private void btnW_Click(object sender, EventArgs e)
{
    txtCategory.Text += btnW.Text;      
}

enter image description here

但我需要多个textbox,如果专注于textbox1它会在text textbox1一个if TextBox2重点键盘button中添加TextBox2 }只会影响192.168.5.3

像真正的键盘功能一样 在.Net 3.5版本

在屏幕截图中看到

4 个答案:

答案 0 :(得分:0)

首先找到焦点文本框,然后在该框中设置文本:

private void btnW_Click(object sender, EventArgs e)
{
    Func<Control, TextBox> FindFocusedTextBox(Control control)
    {
        var container = this as IContainerControl;
        while (container != null)
        {
            control = container.ActiveControl;
            container = control as IContainerControl;
        }
        return control as TextBox;
    }

    var focussedTextBox = FindFocusedTextBox(this);
    if(focussedTextBox != null)
        focussedTextBox.Text += btnW.Text;
}

脚注:找到重点来自:What is the preferred way to find focused control in WinForms app?

答案 1 :(得分:0)

我想建议你一个选择。希望它能帮助你

在页面中声明一个全局TextBoxObject,并将当前聚焦的文本框分配给该对象。将有一个事件处理程序让它为btnW_Click所有按钮。然后你可以添加文本到焦点文本框。请参阅以下代码:

TextBox TextBoxObject; // this will be global

// Event handler for all button
private void btnW_Click(object sender, EventArgs e)
{
   if(TextBoxObject!=null)
   {
      TextBoxObject.Text += btnW.Text;   // This will add the character at the end of the current text
      // if you want to Add at the current position means use like this
        int currentIndex = TextBoxObject.SelectionStart;
      TextBoxObject.Text = TextBoxObject.Text.Insert(currentIndex, btnW.Text);
   }
}

您必须使用以下代码将焦点指定给文本框:

private void textBox2_Click(object sender, EventArgs e)
{
    TextBoxObject = textBox1;   
}

答案 2 :(得分:0)

试试这个:

object obj;
private void btnW_Click(object sender, EventArgs e)
{
    if (obj != null)
    {
        (obj as TextBox).Text += btnW.Text;
    }
}
private void txtCategory_Click(object sender, EventArgs e)
{
    obj = txtCategory;
}
private void textBox1_Click(object sender, EventArgs e)
{
    obj = textBox1;
}

答案 3 :(得分:0)

试试这个:

这对你有帮助。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace StackOverflow
{    
public partial class Form2 : Form
{
    TextBox txtName; 
    public Form2()
    {
        InitializeComponent();
    }

    private void textBox1_Click(object sender, EventArgs e)
    {
        txtName = textBox1;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        if (txtName != null)
        {
            txtName.Text += button1.Text;                                
        }
    }
    private void button2_Click(object sender, EventArgs e)
    {
        if (txtName != null)
        {
            txtName.Text += button2.Text;             
        }
    }
    private void textBox2_Click(object sender, EventArgs e)
    {
        txtName = textBox2;
    }
}
}