分class个控件

Sub-class a control

所以我知道如何创建子classes并调用它们,但是当我必须调用/使用控件的子class时我迷路了:例如:

   public class KeyboardButton : Button
    {
        public void SimulateButtonDown()
        {
            this.OnMouseDown(new MouseEventArgs(MouseButtons.Left, 0, 1, 1, 0));
        }

        public void SimulateButtonUp()
        {
            this.OnMouseUp(new MouseEventArgs(MouseButtons.Left, 0, 1, 1, 0));
        }
    }

this article 中创建。 如何使用,尤其是当我有多个控制按钮时,我想调用方法 "SimulateButtonDown()".

您使用的是 WinForms 还是 WPF?为了这个答案,我将假设 WinForms。

首先,将您在此处发布的代码添加到您的 WinForms 项目的某处。然后编译它。这样做之后,KeyboardButton 应该会自动添加到您的工具箱中。在 Visual Studio 的设计器中打开一个窗体或用户控件,您应该会看到一个名为 "YourProjectName Components" 的部分。此部分应包含 KeyboardButton。只需将其拖放到您的表单或用户控件上即可。

如果您想替换现有窗体或用户控件上的现有按钮,更新 xxx.Designer.cs 中的代码可能更容易。 (注意:编辑 xxx.Designer.cs 文件时要小心。)在解决方案资源管理器中,找到具有要替换的按钮的窗体或用户控件。展开 form/user 控件的节点,您应该会看到一个名为 Form1.Designer.cs 的文件。双击打开该文件。在那里,对于每个现有按钮,您应该看到诸如 this.saveButton = new System.Windows.Forms.Button(); 之类的行。将 System.Windows.Forms.Button 替换为 YourNamespace.KeyboardButton。您还会看到类似 private System.Windows.Forms.Button saveButton; 的行。也在那里替换命名空间和 class 名称。

在 form/user 控件上设置 KeyboardButton 后,您可以从 form/user 控件中调用 SimulateButtonDownSimulateButtonUp编写类似 saveButton.SimulateButtonUp().

的代码