获得在C#中聚焦元素的名称 [英] Get the name of the Focused element in C#

查看:95
本文介绍了获得在C#中聚焦元素的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有在C#中的函数,可以返回焦点元素的名称,并显示在一个文本框或东西吗?

Is there a function in C# that can return the Name of the Focused element and display it in a text-box or something?

推荐答案

或者你可以做这样的事情...

or you can do something like this...

  using System.ComponentModel;
  using System.Data;
  using System.Drawing;
  using System.Linq;
  using System.Text;
  using System.Windows.Forms;
  using System.Runtime.InteropServices;

namespace WindowsFormsApplication1
{
   public partial class Form1 : Form
   {
       public Form1()
       {
            InitializeComponent();            
       }

      private void button1_Click(object sender, EventArgs e)
      {

        MessageBox.Show(GetFocusControl());
      }

      [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Winapi)]
      internal static extern IntPtr GetFocus();

      private string GetFocusControl()
      {
        Control focusControl = null;
        IntPtr focusHandle = GetFocus();
        if (focusHandle != IntPtr.Zero)
            focusControl = Control.FromHandle(focusHandle);
        if (focusControl.Name.ToString().Length == 0)
            return focusControl.Parent.Parent.Name.ToString();
        else
            return focusControl.Name.ToString();
      }
   }
 }

这篇关于获得在C#中聚焦元素的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆