winform 获取焦点
时间: 2023-12-10 07:04:07 浏览: 46
以下是两种在C# Winform中获取焦点的方法:
1. 使用Focus方法
```csharp
// 在窗体的Activated事件中使用textbox的Focus()方法
private void Form1_Activated(object sender, EventArgs e)
{
textBox1.Focus();
}
```
2. 使用LostFocus事件和SetForegroundWindow方法
```csharp
// 添加焦点丢失监听
private void textBox1_LostFocus(object sender, EventArgs e)
{
// 新建线程等待1秒后重新获取焦点
new Thread(new ThreadStart(delegate
{
Thread.Sleep(1000);
if (TopMost)
SetForegroundWindow(ptr);
})).Start();
}
```
相关问题
winform 获取焦点所在的控件相对于控件的 X 坐标和 Y 坐标
要获取焦点所在控件相对于控件的 X 坐标和 Y 坐标,可以使用以下代码:
```
int x = this.ActiveControl.Location.X;
int y = this.ActiveControl.Location.Y;
```
其中,`this.ActiveControl` 表示当前拥有焦点的控件,`Location` 表示控件在其父容器中的位置,`X` 和 `Y` 分别表示横坐标和纵坐标。注意,这里的坐标是相对于控件所在容器的坐标。
winform中picturebox获取焦点
在Winform中,PictureBox控件可以通过设置Focus()方法来获取焦点。通过设置PictureBox的TabStop属性为true,可以使该控件具有可获得焦点的能力。当用户点击PictureBox控件时,该控件会自动获得焦点,并且在该控件上按下Tab键时,也会自动切换到该控件。
以下是获取PictureBox焦点的代码示例:
```csharp
private void pictureBox1_Click(object sender, EventArgs e)
{
pictureBox1.Focus();
}
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)