C#, Introduction to Desktop Programming (01) - Button Button Properties and Events, Dynamic Creation, Shortcut Keys, Control Array and Custom Button

This article is the first article in the "Introduction to Desktop Programming" series.

"Desktop Programming Introduction" series of articles mainly introduce various components of desktop programming, Button, ComboBox, Panel, WebBrowser. . . . . .

There are many similar articles, with different depths and levels.

1 Desktop Programming

1.1 Graphical User Interface (GUI)

Graphical User Interface (Graphical User Interface, referred to as GUI, also known as graphical user interface) refers to the computer operation user interface displayed in a graphical way.

Graphical user interface is an interface display format for human-computer communication, allowing users to use input devices such as a mouse to manipulate icons or menu options on the screen to select commands, call files, start programs, or perform other tasks. Graphical user interfaces have many advantages over character interfaces, where routine tasks are accomplished by entering text or character commands from the keyboard. The graphical user interface is composed of windows, drop-down menus, dialog boxes and their corresponding control mechanisms, which are standardized in various new applications, that is, the same operation is always done in the same way. In the graphical user interface, the user What is seen and manipulated are graphic objects, and the technology of computer graphics is applied.

Although Windows, iOS, and Andriod are called operating systems (desktops), they are actually typical GUI desktop applications.

1.2 Desktop Applications

The so-called desktop programming refers to writing software that runs on desktop computers (desktops, notebooks, servers, workstations, etc.) Windows/Linux/iOS operating systems and has a graphical user interface (GUI).

Desktop programming development seems to be on the wane, and that's what it seems. Mobile phone software is mostly entertainment and life applications, but the software that can really influence and support social progress is all desktop software.

The backwardness of Chinese software is mainly due to the backwardness of desktop software. More than 90% of desktop software is foreign software, and domestic software is very small.

Writing desktop programming is the main embodiment of a programmer's true ability and level.

1.3 What languages ​​are available for developing desktop GUI applications?

The so-called "the ruler is long and the inch is short". Different computer languages ​​are like different weapons, each with its own areas of expertise.

(1) FORTRAN is better than scientific computing, but it is difficult to build GUI;

(2) Python is good at building small, building block, and experimental programs, but it is powerless to develop practical and industrial software; it is especially not suitable for team development;

(3) C/C++ is good at developing basic software, operating system and embedded software, and it takes more effort to develop large-scale software and web applications;

(4) GO is good at developing WEB, and has many shortcomings, such as being unable to cope with the development of scientific computing;

(5) Java and C# are versatile languages ​​suitable for various development needs, multi-platform, high-efficiency, and open source; java belongs to Oracle, which is not completely open source; C# belongs to the foundation, and has been completely open source. Its compiler All fully open source. But C# is inseparable from Frameworks.NET or .NET Core or .NET exclusively developed by Microsoft .

Sadly, there is no language created by the Chinese.

In theory, almost all computer languages ​​can support the development of desktop GUI applications, such as: C#, Visual Basic, Visual Foxpro, java, C++, etc.

The difference lies in different GUI libraries and language ecology.

There have been many excellent development environments in history, such as Visual Basic, Turbo Pascal, C++ Builder and so on.

Currently the best GUI development environment is Visual Studio C# .

1.4 Program Components (Unit, also known as Controls)

A program component is a programmable, reusable software unit that contains combined functionality.

A program component may be a program unit related to a GUI and an interface, or merely provide computing and other capabilities.

Desktop programming generally refers to units that are readily used to assemble applications as components. Like building blocks.

The Visual Studio left sidebar - Toolbox, shows a large number of system prefabricated components that can be used.

You can also design and publish personalized components, called "custom components" or "component customization".

Button is one of the essential components in C# development, "button" is also.

This series of articles starts with this component.

2 Button routine programming

This section introduces the creation of Button, common properties Attributes and event Event.

All C# components can be created in Visual Studio and manually set in the "Properties Window", or created, set and modified in the program.

The difference is: beginners generally use Visual Studio, which is easy to use and understandable; experts are happy to do it in the program.

The use of components includes three links : creating components, setting and modifying properties , and creating and modifying events .

2.1 Button creation

2.1.1 Simple, integrated development environment Visual Studio to create Button

Three intuitive and convenient Button creation methods:

(1) On the left toolbar, double-click Button;

A Button button will appear on the Form1.cs [Design] interface on the right;

In this way, the position of the button is the upper left corner of the current control, each time you want to drag and so on;

(2) On the left toolbar, click Button;

Click on the appropriate position of the Form1.cs [Design] interface on the right, a button will appear, and then adjust its size;

(3) The third method, copy and paste

Click an already created button Button, Ctrl+C and then Ctrl+V in the appropriate container;

Copy and paste can copy multiple or even all components at once!

2.1.2 Flexible and dynamic creation of Button

The Button created above is finally implemented in Form1.Designer.cs in code:

Form1.Designer.cs is the code related to window design (GUI interface) automatically generated by Visual Studio.

This method is much higher than xml html json and so on!


namespace Legalsoft.Truffer.CAD
{
    partial class Form1
    {
        private void InitializeComponent()
        {
            //...
            this.button3 = new System.Windows.Forms.Button();
            
            //...
            // 
            // button3
            // 
            this.button3.Location = new System.Drawing.Point(217, 31);
            this.button3.Name = "button3";
            this.button3.Size = new System.Drawing.Size(139, 60);
            this.button3.TabIndex = 33;
            this.button3.Text = "button3";
            this.button3.UseVisualStyleBackColor = true;
            this.button3.Click += new System.EventHandler(this.button3_Click);
        }
        
        //...
        private System.Windows.Forms.Button button3;
        //...
    }
}

因而,大家如法炮制即可。

在任何有 的代码内用下面这种方式动态创建Button:

using System.Windows.Forms;
    
namespace Legalsoft.Truffer.CAD
{
    partial class Form1
    {
        void some()
        {
            Button button3 = new Button();
            button3.Text = "Compile";
            button3.Size = new Size(100, 30);
            button3.Location = new Point(0, 0);
            button3.Click += new System.EventHandler(button3_OnClick);
            //this.Controls.Add(button);
            button3.Parent = Panel1;
        }

        void button3_OnClick()
        {
            MessageBox.Show("click button3!");
        }
    }
}

2.2 Button属性

2.2.1 Name 名称

没什么好说的,每个控件都需要独立的一个名字。

如同人的身份证号码。

俺一般习惯命名为 btn???。

Visual Studio 按顺序自然定义为 Button1, Button2 ...

自主创建,则可以这样:

Button btnCalculate = new Button();

2.2.2 Parent 父单元

Parent属性定义了Button的父单元。

比如我喜欢把 Button 放在 Panel 中,其定义是这样的:

btnCalculate.Parent = Panel1;

2.2.3 Location 位置

btnCalculate.Location = new Point(50,60);

也可以用分别设置横坐标、纵坐标的方式给定Button位置。

2.2.3.1 Left 横坐标

btnCalculate.Left = 50;

2.2.3.2 Top 纵坐标

btnCalculate.Left = 60;

2.2.4 Size 尺寸

btnCalculate.Size = new Size(110,50);

也可以用分别设置宽度、高度的方式给定Button尺寸。

2.2.4.1 Width 宽度

btnCalculate.Width = 110;

2.2.4.2 Height 高度

btnCalculate.Height = 50;

2.2.5 Text 文字

文字是显示在 Button 的字符串。

它区别于 Name,Name 用于访问Button,Text用于显示。

btnCalculate.Text = "Compile";

2.2.6 Cursor 光标

不同的组件,定义不同的光标,利于用户识别与操作。

一般把 Button 的光标设置为 手指比较好看。

btnCalculate.Cursor = Cursors.Hand;

2.2.7 BackColor 背景颜色

btnCalculate.BackColor = Colors.DarkGray;

这个需要学习 Colors 知识,以后专门介绍。

2.2.8 Enabled 是否可用

如果赋值:

btnCalculate.Enabled = false;

则,btnCalculate 就变成灰色,无法点击了。

通过设置另外一个或一些 Button 的 Enabled,减少用户误操作。

比如 btnStart 与 btnStop 两个按钮是互斥的。

可以这样编写:


private void btnStart_Click(object sender, EventArgs e)
{
    {
        // start按钮对应的启动代码
        ;
    }
    btnStart.Enabled = false;
    btnStop.Enabled = true;
}

private void btnStop_Click(object sender, EventArgs e)
{
    {
        // stop按钮对应的停止代码
        ;
    }
    btnStart.Enabled = true;
    btnStop.Enabled = false;
}

2.2.9 Visible 是否可见

如果赋值:

btnCalculate.Visible = false;

则,btnCalculate 就从界面消失了。

通过设置另外一个或一些 Button 的 Visible,也减少用户误操作。

本文作者喜欢控制 Panel 的 Visible ,而不是 Button Visible,有很多好处。

2.2.10 其他属性

2.2.10.1 FlayStyle 控件样式

2.2.10.2 Image 设置控件图像

2.2.10.3 ImageAlign 图像对齐方式

2.2.10.4 ImageList 图像ImageList索引值

2.2.10.5 Tabindex 控件顺序索引

2.2.10.6 TextAlign 文本对齐方式

2.2.11 事件Event

组件的事件,是组件在发生点击等事件的时候(可分前、中、后)进行相应处理的一个对应关系。

Button需要关注的事件,就是点击(单击)事件了。

所有C#组件的事件,既可以在 Visual Studio 中创建、以及在“属性窗口”手工设置,也可以在程序中创建、设置与修改。

区别是:初学者一般用Visual Studio,容易上手,无可厚非;高手乐于在程序中进行。

2.2.11.1 VS创建

Form1.cs

private void btnCalculate_Click(object sender, EventArgs e)
{
    //。。。
}

Form1.Designer.cs

this.btnCalculate.Click += new System.EventHandler(this.btnCalculate_Click);

2.2.11.2 编程创建事件

参阅前面的代码(Form1.Designer.cs):

button3.Click += new System.EventHandler(button3_OnClick);

3 Button数组

控件数组与事件

许多时候会有一堆同样的组件,比如26个按钮,每个都修改其属性、事件岂不是很麻烦。

因而,可以使用控件数组来批量处理。

程序员都是懒虫,也是最爱创新的伙计。

创建控件数组(组件数组很难听),两种方式:

3.1 如果是用 Visual Studio 创建的 Button

    Button[] bts = new Button[2];
    bts[0] = Button1;
    bts[1] = Button2;

3.2 如果是动态创建Button,则可以直接赋值给数组即可。

下面的代码改编自:

https://www.cnblogs.com/laoshuboke/p/4654593.html

namespace Legalsoft.Truffer.CAD
{
    private void Form1_Load(object sender, EventArgs e)
    {
        Button[] but = new Button[10];
        for (int i = 0; i < 10; i++)
        {
            but[i] = new Button();
            but[i].Text = "按钮" + i;
            but[i].Left = 82 * i;
            but[i].Width = 80;
            this.Controls.Add(but[i]);
            //绑定事件
            but[i].Click += new System.EventHandler(this.but_Click);
        }
    }

    private void but_Click(object sender,System.EventArgs e)
    {
        //用sender 判定是那个控件
        MessageBox.Show(((Button)sender).Text+"01");
    }
}

4、C# Button快捷键实现方法

萝卜白菜,各有所爱。Button的操作,有人喜欢点击,也有人喜欢用快捷键。

以下是实现快捷键触发Button点击事件的代码。来自于:

https://www.cnblogs.com/zzzzw/p/4447206.html

本文讲解了三种方法实现C# button快捷键,如Alt + *(按钮快捷键),Ctrl+*及其他组合键等。

4.1 C# button快捷键之第一种:Alt + *(按钮快捷键)

给Button、Label、MenuStrip等控件设置Text属性时在名字后边加&键名就可以了,

比如:button1.text= "确定(&O)"。就会有快捷键了,这时候按Alt+O就可以执行按钮单击事件。

4.2 C# button快捷键之第二种:Ctrl+*及其他组合键

Ctrl+快捷键需要通过截获 Windows Form 的鼠标事件实现。

首先要设置 Form1 的属性(向窗体注册键盘事件);

Form1. KeyPreview = True;

然后使用窗体的KeyDown事件(在首次按下某个键时发生).

C# button快捷键之实例代码:

namespace Legalsoft.Truffer.CAD
{
    private void Form1_KeyDown(object sender, KeyEventArgs e)  
    {     
        if (e.KeyCode == Keys.F && e.Control)   
        {         
            //将Handled设置为true,指示已经处理过KeyPress事件         
            e.Handled = true;   
            //执行单击button1的动作   
            button1.PerformClick();        
        }  
    }
}

4.3 C# button快捷键之第三种方法

这个方法有点绕,是个很好玩的思路。

给Form添加一个菜单项contextMenuStrip1,将其邦定到Button1。

给contextMenuStrip1添加一个item,然后为它设置快捷键(就是你想加在button上的快捷键),

并且将它的Visible属性设为false。

这样,C# Button快捷键设置成功。

5 Button自定义(继承与重写Button类)

5.1 渐变色的按钮

代码来自于:

https://www.cnblogs.com/laoshuboke/p/6060866.html

修改了一点BUG。

[Legalsoft.Truffer.CAD.Controls.GradientButton.cs]

using System;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Collections.Generic;
using System.Windows.Forms;
using System.ComponentModel;

namespace Legalsoft.Truffer.CAD
{
    /// <summary>
    /// 渐变色的按钮 C# Button
    /// https://www.cnblogs.com/laoshuboke/p/6060866.html
    /// </summary>
    public class GradientButton : Button
    {
        Rectangle r { get; set; }
        private Brush _myBrush { get; set; } = null;
        private Color _color1 { get; set; } = Color.FromArgb(0, 255, 0);
        private Color _color2 { get; set; } = Color.FromArgb(0, 0, 255);
        private Color color3 { get; set; }
        private Color color4 { get; set; }

        [Category("设置"), Description("渐变开始颜色")]
        public Color color1
        {
            get { return _color1; }
            set { _color1 = value; }
        }

        [Category("设置"), Description("渐变结束颜色")]
        public Color color2
        {
            get { return _color2; }
            set { _color2 = value; }
        }

        public void ButtoonNew()
        {
            r = new Rectangle(0, 0, 150, 80);
            _myBrush = new LinearGradientBrush(r, color1, color2, LinearGradientMode.Vertical);
        }

        public Brush MyBrush
        {
            get { return _myBrush; }
            set { _myBrush = value; }
        }

        protected override void OnResize(EventArgs e)
        {
            base.OnResize(e);
            r = new Rectangle(0, 0, this.Width, this.Height);
            MyBrush = new LinearGradientBrush(r, color1, color2, LinearGradientMode.Vertical);
        }

        protected override void OnMouseLeave(EventArgs e)
        {
            base.OnMouseLeave(e);
            r = new Rectangle(0, 0, this.Width, this.Height);
            color1 = color3;
            color2 = color4;
            MyBrush = new LinearGradientBrush(r, color1, color2, LinearGradientMode.Vertical);
        }

        protected override void OnMouseEnter(EventArgs e)
        {
            base.OnMouseEnter(e);
            color3 = this.color1;
            color4 = this.color2;
            r = new Rectangle(0, 0, this.Width, this.Height);
            MyBrush = new LinearGradientBrush(r, color4, color3, LinearGradientMode.Vertical);
        }

        protected override void OnPaint(PaintEventArgs pevent)
        {
            base.OnPaint(pevent);
            Graphics g = pevent.Graphics;
            g.FillRectangle(MyBrush, this.ClientRectangle);
            StringFormat strF = new StringFormat();
            strF.Alignment = StringAlignment.Center;
            strF.LineAlignment = StringAlignment.Center;
            g.DrawString(this.Text, this.Font, new SolidBrush(Color.White), this.ClientRectangle, strF);
        }
    }
}

动态创建渐变色按钮的代码。

也可以从左侧工具栏拖过去。

GradientButton xb = new GradientButton();
xb.ButtoonNew();
xb.Left = 110;
xb.Top = 50;
xb.Width = 110;
xb.Height = 50;
xb.Parent = tabPage2;
xb.Text = "G-BUTTON";

5.2 带圆角的Button

代码来自于:

http://t.zoukankan.com/zzh1236-p-3044686.html

修改了一些BUG。

[Legalsoft.Truffer.CAD.Controls.RoundButton.cs]

using System;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Collections.Generic;
using System.Windows.Forms;

namespace Legalsoft.Truffer.CAD
{
    public enum ButtonStyle
    {
        /// <summary>
        /// 正常为选中按钮
        /// </summary>
        ButtonNormal,
        /// <summary>
        /// 获得焦点的按钮
        /// </summary>
        ButtonFocuse,
        /// <summary>
        /// 鼠标经过样式
        /// </summary>
        ButtonMouseOver,
        /// <summary>
        /// 获得焦点并鼠标经过
        /// </summary>
        ButtonFocuseAndMouseOver
    }

    /// <summary>
    /// 自定义GDI工具,绘制按钮
    /// </summary>
    public class Button_GDI
    {
        /// <summary>
        /// 绘制圆形按钮(用法同矩形按钮)
        /// </summary>
        /// <param name="text"></param>
        /// <param name="g"></param>
        /// <param name="Location"></param>
        /// <param name="r"></param>
        /// <param name="btnStyle"></param>
        public static void DrawCircleButton(string text, Graphics g, Point Location, int r, ButtonStyle btnStyle)
        {
            Graphics Gcircle = g;
            Rectangle rect = new Rectangle(Location.X, Location.Y, r, r);
            Pen p = new Pen(new SolidBrush(Color.Black));
            Gcircle.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
            Gcircle.DrawEllipse(p, rect);
            if (btnStyle == ButtonStyle.ButtonFocuse)
            {
                Gcircle.FillEllipse(new SolidBrush(ColorTranslator.FromHtml("#338FCC")), rect);
            }
            else if (btnStyle == ButtonStyle.ButtonMouseOver)
            {
                Gcircle.FillEllipse(new SolidBrush(ColorTranslator.FromHtml("#EAC100")), rect);
            }
            else if (btnStyle == ButtonStyle.ButtonFocuseAndMouseOver)
            {
                Gcircle.FillEllipse(new SolidBrush(ColorTranslator.FromHtml("#EAC100")), rect);
            }

            p.DashStyle = DashStyle.Dash;
            if (btnStyle != ButtonStyle.ButtonNormal)
            {

                Gcircle.DrawEllipse(p, new Rectangle(rect.X + 2, rect.Y + 2, rect.Width - 4, rect.Height - 4));//虚线框
            }
            Gcircle.FillEllipse(new SolidBrush(Color.WhiteSmoke), new Rectangle(rect.X + 3, rect.Y + 3, rect.Width - 6, rect.Height - 6));
            StringFormat sf = new StringFormat();
            sf.Alignment = StringAlignment.Center;
            sf.LineAlignment = StringAlignment.Center;
            Gcircle.DrawString(text, new Font(new FontFamily("宋体"), 10), new SolidBrush(Color.Black), rect, sf);
            p.Dispose();
        }

        /// <summary> 
        /// 绘制圆角按钮
        /// </summary> 
        /// <param name="Text">要绘制的文字</param>
        /// <param name="g">Graphics 对象</param> 
        /// <param name="rect">要填充的矩形</param> 
        /// <param name="btnStyle"></param>
        public static void DrawRoundButton(string Text, Graphics g, Rectangle rect, ButtonStyle btnStyle)
        {
            g.SmoothingMode = SmoothingMode.AntiAlias;
            Rectangle rectangle = rect;
            Brush b = b = new SolidBrush(Color.Black);
            if (btnStyle == ButtonStyle.ButtonFocuse)
            {
                b = new SolidBrush(ColorTranslator.FromHtml("#338FCC"));
            }
            else if (btnStyle == ButtonStyle.ButtonMouseOver)
            {
                b = new SolidBrush(ColorTranslator.FromHtml("#C6A300"));
            }
            else if (btnStyle == ButtonStyle.ButtonFocuseAndMouseOver)
            {
                b = new SolidBrush(ColorTranslator.FromHtml("#C6A300"));
            }
            g.DrawPath(new Pen(b), GetRoundRectangle(rectangle, 8));
            rectangle = new Rectangle(rect.X + 2, rect.Y + 2, rect.Width - 4, rect.Height - 4);
            Pen p = new Pen(Color.Black, 0.5f);
            p.DashStyle = DashStyle.Dash;
            if (btnStyle == ButtonStyle.ButtonFocuse || btnStyle == ButtonStyle.ButtonFocuseAndMouseOver)
            {
                g.DrawPath(new Pen(b), GetRoundRectangle(rectangle, 8));
            }
            g.FillPath(new SolidBrush(Color.WhiteSmoke), GetRoundRectangle(rectangle, 8));

            StringFormat sf = new StringFormat();
            sf.Alignment = StringAlignment.Center;
            sf.LineAlignment = StringAlignment.Center;
            g.DrawString(Text, new Font("宋体", 10), new SolidBrush(Color.Black), rectangle, sf);
            p.Dispose();
            b.Dispose();
            g.SmoothingMode = SmoothingMode.Default;
        }

        /// <summary> 
        /// 根据普通矩形得到圆角矩形的路径 
        /// </summary> 
        /// <param name="rectangle">原始矩形</param> 
        /// <param name="r">半径</param> 
        /// <returns>图形路径</returns> 
        private static GraphicsPath GetRoundRectangle(Rectangle rectangle, int r)
        {
            int l = 2 * r;
            // 把圆角矩形分成八段直线、弧的组合,依次加到路径中 
            GraphicsPath gp = new GraphicsPath();
            gp.AddLine(new Point(rectangle.X + r, rectangle.Y), new Point(rectangle.Right - r, rectangle.Y));
            gp.AddArc(new Rectangle(rectangle.Right - l, rectangle.Y, l, l), 270F, 90F);

            gp.AddLine(new Point(rectangle.Right, rectangle.Y + r), new Point(rectangle.Right, rectangle.Bottom - r));
            gp.AddArc(new Rectangle(rectangle.Right - l, rectangle.Bottom - l, l, l), 0F, 90F);

            gp.AddLine(new Point(rectangle.Right - r, rectangle.Bottom), new Point(rectangle.X + r, rectangle.Bottom));
            gp.AddArc(new Rectangle(rectangle.X, rectangle.Bottom - l, l, l), 90F, 90F);

            gp.AddLine(new Point(rectangle.X, rectangle.Bottom - r), new Point(rectangle.X, rectangle.Y + r));
            gp.AddArc(new Rectangle(rectangle.X, rectangle.Y, l, l), 180F, 90F);
            return gp;
        }
    }

    /// <summary>
    /// 自定义带圆角的C# Button
    /// </summary>
    public class RoundButton : Button
    {
        private bool mouseover = false;

        public RoundButton()
        {
            this.Cursor = Cursors.Hand;
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            //在这里用自己的方法来绘制Button的外观(其实也就是几个框框)
            Graphics g = e.Graphics;
            g.Clear(Color.WhiteSmoke);
            Rectangle rect = e.ClipRectangle;
            rect = new Rectangle(rect.X, rect.Y, rect.Width - 1, rect.Height - 2);
            if (mouseover)
            {
                if (Focused)
                {
                    Button_GDI.DrawRoundButton(this.Text, g, rect, ButtonStyle.ButtonFocuseAndMouseOver);
                    return;
                }
                Button_GDI.DrawRoundButton(this.Text, g, rect, ButtonStyle.ButtonMouseOver);
                return;
            }
            if (Focused)
            {
                Button_GDI.DrawRoundButton(this.Text, g, rect, ButtonStyle.ButtonFocuse);
                return;
            }
            Button_GDI.DrawRoundButton(this.Text, g, rect, ButtonStyle.ButtonNormal);
        }

        protected override void OnMouseEnter(EventArgs e)
        {
            mouseover = true;
            base.OnMouseEnter(e);
        }
        protected override void OnMouseLeave(EventArgs e)
        {
            mouseover = false;
            base.OnMouseLeave(e);
        }
    }
}

动态创建渐圆角按钮的代码。

RoundButton yb = new RoundButton();
yb.Left = 230;
yb.Top = 50;
yb.Width = 110;
yb.Height = 50;
yb.Parent = tabPage2;
yb.Text = "R-BUTTON";

也可以从左侧工具栏拖过去。

POWER BY 315SOFT.COM AND TRUFFER.CN

虽然本文给出了一些自定义等拓展Button拓展开发代码,但不建议大家在这方面花费太多时间,

这不代表任何编程能力,技巧而已,

应该将时间花在数值计算、算法等方面。

Guess you like

Origin blog.csdn.net/beijinghorn/article/details/128568352