【问题标题】:How to detect if control is button or not in C# [duplicate]如何在C#中检测控件是否是按钮[重复]
【发布时间】:2020-04-02 12:33:41
【问题描述】:

我想在我的表单中将所有按钮的光标类型更改为“手”。但是代码不起作用。有人可以帮忙吗? ) 这是代码:

 foreach (Control control in this.Controls)
 {
      if (control is Button)
      {
           control.Cursor = Cursors.Hand;
      }
  }

【问题讨论】:

  • 这是 ASP.NET 吗?温窗体?赛马林? Control和Button有哪些类型?

标签: c#


【解决方案1】:

您正在正确检查控件是否为 Button 类型。但是在更改光标之前,您需要将其转换为 Button 控件(不是通用控件)。

if (control is Button)
{
    (control as Button).Cursor = Cursors.Hand;
}

【讨论】:

    【解决方案2】:

    您可以使用模式匹配语法。试试这个:

     foreach (Control control in this.Controls)
     {
          if (control is Button b)
          {
               b.Cursor = Cursors.Hand;
          }
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-25
      • 2022-10-02
      • 1970-01-01
      • 2020-05-19
      • 1970-01-01
      • 2015-08-19
      • 1970-01-01
      相关资源
      最近更新 更多