今天在使用.net winform中的radiobutton中遇到两个问题,一是窗体中的控件不能按tabindex顺序执行,二是radiobutton获得tab焦点后不能实现选中,
页面如下:
解决思路如下
1.捕获textbox的键盘事件,如果在textbox中按下的是tab键,自动使下一个获得tab焦点的单选按钮选中
2.设置页面中控件的tabindex顺序
代码如下
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Shown(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
rb1.TabIndex = 0;
tb1.TabIndex = 1;
rb2.TabIndex = 2;
textBox2.TabIndex = 3;
rb3.TabIndex = 4;
textBox3.TabIndex = 5;
rb1.Focus();
}
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
Control ctl = this.ActiveControl;
if (keyData == Keys.Tab)
{
Console.WriteLine(ctl.Name);
if (ctl.Name == "tb1")
{
rb2.Checked = true;
rb1.Checked = false;
rb3.Checked = false;
}
if (ctl.Name == "textBox2")
{
rb2.Checked = false;
rb1.Checked = false;
rb3.Checked = true;
}
if (ctl.Name == "textBox3")
{
rb2.Checked = false;
rb1.Checked = true;
rb3.Checked = false;
}
}
bool ret = base.ProcessCmdKey(ref msg, keyData);
return ret;
}
}
}