我在窗体中动态生成了几种控件,想在单击某个控件时,得到当前的控件。
从网上查有 this.ActiveControl 方法,但这个只能应用在能够得到焦点的控件(比如TextBox等),像Label这样的控件就不行了。
从网上查有 this.ActiveControl 方法,但这个只能应用在能够得到焦点的控件(比如TextBox等),像Label这样的控件就不行了。
解决方案 »
- 请教TreeView新增,删除,向上向下移问题
- C#-TCP"请求的地址无效“
- 我用regasm.exe将dll文件注册进com+后,交给vb6调用,怎么才能知道dll内部的异常?
- c# 调用 搜索引擎
- 莫名其妙的问题!~~~~~~~~~~~~~~~~
- 请问可在SerialPort的DataReceived触发事件程序中,写入SerialPort.Write发送资料吗?
- 定位到DATAGRID指定的值的问题
- 关于c#自动升级winfrom的问题??孟子E章请进,其他高手帮忙啦!
- C#中字符匹配方法
- 数据行删除后如何访问该行的数据!
- 求 DataGridView 在每一列最后添加一个按钮代码
- 如何在一个进程启动时想另一个进程发送通知(两个都是C#的)
//可根据生成的控件的特定标识(如Name,Tag等),从父控件中去遍历查找
//如:(可写在某个动态注册的事件中)
Control parent = this.Parent;
if(parent == null || parent.Controls.Count== 0) return;
foreach(Control c in parent.Controls)
{
if(c is Label)
{
Label lbl = c as Label;
if(lbl.Name == "lbl5")
{
//code
}
}
}
Button btn = new Button();
btn.Click += new EventHandler(this.btn_Click);
this.Controls.Add(btn);按钮单击事件:
private void btn_Click(object sender, EventArgs e)
{
Button btn = sender as Button; //这样获取被单击的按钮}
不过有个变通的办法先要添加引用
Accessibility
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;
using System.Runtime.InteropServices;namespace WindowsFormsApplication16
{
public partial class Form1 : Form, IMessageFilter
{
public Form1()
{
InitializeComponent();
Application.AddMessageFilter(this);
} public bool PreFilterMessage(ref System.Windows.Forms.Message Msg)
{
if (Msg.Msg == 0x201)
if (label1.ClientRectangle.IntersectsWith(new Rectangle( label1.PointToClient(MousePosition),new Size(1,1))))
MessageBox.Show("label1");
return false;
} }
}
搂主如果不想用的话,我再给搂主说个方法吧:你帖子说:
从网上查有 this.ActiveControl 方法,但这个只能应用在能够得到焦点的控件(比如TextBox等),像Label这样的控件就不行了。
其实,Label控件是可以获得焦点的,只不过得强制获得焦点:Label标签控件单击事件:
private void label_Click(object sender, EventArgs e)
{
this.label1.Focus();//点击后,强制获得焦点
这个时候this.ActiveControl应该就等于label1
}不过这种方法不如我在前面说的那个好
这个是我以前回答另外一个人的时候用到了AccessibilityObject才要添加的
For Each vObj As Control In Me.Controls
AddHandler vObj.MouseDown, AddressOf Controls_MouseDown
Next
'
Private Sub Controls_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs)
'操作sender
End Sub
在你添加控件的时候 给控件添加鼠标事件
2 使用坐标判断用GetChildAtPoint方法获取控件 this.Text=Form1.MousePosition.ToString();
int _X=Form1.MousePosition.X;
int _Y=Form1.MousePosition.Y;
_X-=this.Left; _Y -= this.Top + 25; Control _SetControl=this.GetChildAtPoint(new Point(_X, _Y)); if (_SetControl != null) this.Text = _SetControl.Name;