[WinForm Detailed Tutorial 3] NumericUpDown, PictureBox, RichTextBox and three Timer controls in WinForm

1. NumericUpDown

NumericUpDownA control is a control for numeric input and display, typically allowing the user to select a numeric value. It includes a text box that displays the current value, and up and down buttons that the user can click to increase or decrease the value. This kind of control is very useful when the user needs to enter data such as quantity, age, quantity, etc.

Attributes:

NumericUpDownControls have many properties, some of which are commonly used:

  • Value: used to get or set the value currently displayed by the NumericUpDown control.
  • Minimum: Specify the minimum value allowed to be entered.
  • Maximum: Specify the maximum value allowed for input.
  • Increment: Specify how much the value increases or decreases when the up or down button is pressed.
  • DecimalPlaces: Specify the number of digits after the decimal point, and enter decimals if necessary.
  • ThousandsSeparator: If set to true, thousands separators will be inserted into numeric values.

method:

NumericUpDownControls provide some methods to manipulate the behavior of the control, two common methods are:

  • UpButton(): Simulate the user to click the up button to increase the value.
  • DownButton(): Simulate the user clicking the down button to decrease the value.

event:

  • ValueChanged: Event triggered when the value of the NumericUpDown control changes. You can associate an event handler with this event to perform specific actions when the value changes.

Case:

public partial class FrmNumericUpDown : Form
{
    public FrmNumericUpDown()
    {
        InitializeComponent();
    }

    private void FrmNumericUpDown_Load(object sender, EventArgs e)
    {
        // 设置 NumericUpDown 控件的位置和大小
        //numericUpDown1.Location = new Point(50, 50);
        //numericUpDown1.Size = new Size(120, 30);
        // 设置允许输入的最小值和最大值
        numericUpDown1.Minimum = 0;
        numericUpDown1.Maximum = 100;
        // 设置增量值为1
        numericUpDown1.Increment = 1;
        // 设置小数点后的位数为0
        numericUpDown1.DecimalPlaces = 0;
    }

    private void btnSubtraction_Click(object sender, EventArgs e)
    {
        numericUpDown1.DownButton();
    }

    private void btnAdd_Click(object sender, EventArgs e)
    {
        numericUpDown1.UpButton();
    }

    private void numericUpDown1_ValueChanged(object sender, EventArgs e)
    {
        textBox1.Text = numericUpDown1.Value.ToString();
    }
}

Insert image description here

2. PictureBox

PictureBoxcontrol is an image control used to display images in Windows Forms. It is a very common control used to display graphic elements and can be used to display various images such as pictures, icons, bitmaps, etc.

Attributes:

  • Image: used to set or get the image displayed in the PictureBox control. You can display an image by loading an image file through code or by assigning the image directly to this property.
  • ImageLocation: This is a string attribute that specifies the path to the image file to be displayed in PictureBox. When you set the ImageLocation attribute, it will automatically load and display the image at the specified path.
  • SizeMode: The SizeMode attribute is used to control how the image is displayed in PictureBox . Common options include:
    • Normal: The image will be displayed at its original size, which may extend beyond the bounds of the PictureBox control.
    • StretchImage: The image will be stretched to fill the entire PictureBox control.
    • AutoSize: The PictureBox control will automatically resize to fit the dimensions of the image.
    • CenterImage: The image will be displayed in the center of the PictureBox control, maintaining its original size.
    • Zoom: The image will be scaled to fill the PictureBox control but retain the original proportions.

event:

  • Click: Event triggered when the user clicks the PictureBox control. You can associate an event handler with this event to perform specific actions when the user clicks on the image.

Case:

 public partial class frmPictureBox : Form
 {
     public frmPictureBox()
     {
         InitializeComponent();
     }

     private void pictureBox1_Click(object sender, EventArgs e)
     {
         MessageBox.Show("用户单击了图像!");
     }

     private void frmPictureBox_Load(object sender, EventArgs e)
     {
         // 设置 PictureBox 控件的位置和大小
         pictureBox1.Location = new Point(50, 50);
         pictureBox1.Size = new Size(200, 150);
         // 指定要显示的图像文件的路径
         pictureBox1.ImageLocation = "C:\\Users\\24576\\Pictures\\Microsoft.Windows.Photos_8wekyb3d8bbwe!App\\111.jpg";
         // 设置图像显示模式为拉伸以填充整个 PictureBox 控件
         pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;

     }
 }

image-20231025221311835

3.RichTextBox control

RichTextBoxThe control is a rich text editing control that allows users to enter and edit text and supports rich text formatting options such as fonts, colors, styles, etc. Users can create bold, italic, underline text, insert pictures, create hyperlinks, etc. in RichTextBox. This makes RichTextBox very useful in applications that require rich text editing capabilities, such as document editors, chat applications, etc.

Common properties:

The RichTextBox control has many properties, the following are some commonly used properties:

  • Text: Get or set the text content in RichTextBox.
  • SelectionFont: Get or set the font of the currently selected text.
  • SelectionColor: Get or set the color of the currently selected text.
  • SelectionAlignment: Get or set the alignment of the currently selected text (left-aligned, centered, right-aligned, etc.).
  • SelectionBullet: Gets or sets whether the currently selected text has bullets (such as dots).
  • DetectUrls: Indicates whether to automatically detect URLs in text and create hyperlinks.

method:

The RichTextBox control provides some methods to manipulate text and control behavior. The following are some commonly used methods:

  • Find: Used to search and locate the specified string in the text, and optionally specify the starting position and search options of the search.
  • SaveFile: Used to save the content in RichTextBox to a file.
  • LoadFile: Used to load text content from a file into the RichTextBox control.

event:

The RichTextBox control defines some events. The following are some commonly used events:

  • TextChanged: Event triggered when the text content in RichTextBox changes. You can associate an event handler with this event to perform specific actions when the text changes.
  • SelectionChanged: Event triggered when the user changes the selected text.
  • LinkClicked: Event triggered when the user clicks a hyperlink. This is typically used to handle navigation of links within an application.

Case:

 public partial class frmRichTextBox : Form
 {
     public frmRichTextBox()
     {
         InitializeComponent();
     }

     private void frmRichTextBox_Load(object sender, EventArgs e)
     {
         // 向 RichTextBox 中插入富文本内容
         richTextBox1.AppendText("这是一段富文本示例。\n");
         richTextBox1.SelectionFont = new Font("Arial", 12, FontStyle.Bold);
         richTextBox1.SelectionColor = Color.Blue;
         richTextBox1.AppendText("这是粗体蓝色文本。\n");

         // 添加一个超链接
         richTextBox1.AppendText("访问我的网站:");
         richTextBox1.SelectionFont = new Font("Arial", 12, FontStyle.Underline);
         richTextBox1.SelectionColor = Color.Blue;
         richTextBox1.AppendText("https://www.baidu.com\n");
         
         Clipboard.Clear(); //剪贴板清空
         Image bmp = Image.FromFile(@"C:\\Users\\24576\\Pictures\\Microsoft.Windows.Photos_8wekyb3d8bbwe!App\\111.jpg");
         Clipboard.SetImage(bmp);
         richTextBox1.Paste();//将剪贴板中的图片粘贴到控件中
         
     }

     private void richTextBox1_LinkClicked(object sender, LinkClickedEventArgs e)
     {
         //启动进程,将资源与新的Process相关联
         System.Diagnostics.Process.Start(e.LinkText);
     }
 }

其它一些用法
//richTextBox1.LoadFile(@"d:\course.txt", RichTextBoxStreamType.PlainText);//加载文件到控件中
//richTextBox1.SaveFile(@"d:\courseNew.rtf"); //保存文件
//richTextBox1.SelectionAlignment = HorizontalAlignment.Center; //居中
//richTextBox1.SelectionFont = newFont;//设置选定内容或插入点的字体

Insert image description here

4. Timer, System.Timers.Timer and System.Threading.Timer timers

4.1 Timer

  • Function: Mainly used to perform scheduled tasks in Windows applications, and an event will be triggered every specified interval.
  • Threading model: It runs in the UI thread, so UI elements can be modified directly.
  • Attribute:
    • Interval: Set the time interval in milliseconds (ms), for example, 1000ms means 1 second.
  • incident:
    • Tick: Triggered every time the set time interval is reached.
  • Site view
    • Dynamic time display
    • animation
    • Automatically update UI, etc.
  • Performance considerations:
    • If a single execution time exceeds the interval, it will affect the next trigger.
    • The accuracy is poor and not suitable for scenarios that require high-precision timing.

Code example:

public partial class frmTimer : Form
{
    public frmTimer()
    {
        InitializeComponent();
    }

    private void frmTimer_Load(object sender, EventArgs e)
    {
        label1.Text = DateTime.Now.ToString();
        timer1.Enabled = true;
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        label1.Text = "当前的时间是:" + DateTime.Now.ToString();
    }
}

Insert image description here

4.2 System.Timers.Timer

System.Timers.TimerIs a service-based timer that triggers the Elapsed event and performs actions at specified intervals. It is a lightweight timer suitable for performing some scheduled tasks in the background.

Features:

  • System.Timers.Timer is a service-based timer, so it does not rely on the UI thread and can perform operations in the background.
  • Its time interval can be set, and when the specified time interval is reached, the Elapsed event will be triggered.
  • System.Timers.Timer cannot directly modify UI elements because it is not executed by the UI thread.
  • To modify UI elements in System.Timers.Timer, you can use the UI element's Invoke method or 委托 to operate.
  • The operations performed by System.Timers.Timer are time-consuming, but will not cause the UI to become unresponsive, nor will it affect the next trigger.

Common properties:

  • Interval: Gets or sets the timer interval (in milliseconds).
  • Enabled: Gets or sets a value indicating whether the timer is available.

Commonly used methods:

  • Start(): Start the timer to start timing.
  • Stop(): Stop the timer to stop timing.

Common events:

  • Elapsed: An event triggered after the timer interval expires. You can subscribe to this event to perform the required actions.

Code example:

public partial class frmTimersTimer : Form
{
    public frmTimersTimer()
    {
        InitializeComponent();
    }

    private void frmTimersTimer_Load(object sender, EventArgs e)
    {
        System.Timers.Timer timer = new System.Timers.Timer();
        timer.Interval = 1000;
        //timer3.AutoReset = false;//只会引发一次,就停止了
        timer.Elapsed += Timer_Elapsed; //注册事件
        timer.Start();
    }

    int count = 0;
    private void Timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        // 在委托中修改 UI 元素
        Invoke((Action)(() =>
        {
            // 修改 UI 元素
            label1.Text = "当前时间是:" + DateTime.Now.ToString();
        }));

        count += 1;
        if (count > 10)
        {
            System.Timers.Timer timer = (System.Timers.Timer)sender;
            timer.Stop();
        }
    }
}

Insert image description here

4.3 System.Threading.Timer

System.Threading.TimerIs a multi-threaded timer that provides a mechanism to execute methods on thread pool threads at specified intervals. It is a lightweight timer with high accuracy.

Features:

  • System.Threading.Timer provides a mechanism to execute methods within a specified time interval, using thread pool threads to perform operations.
  • Even if the execution time of the callback method exceeds the specified time interval, it will not affect the next trigger, because System.Threading.Timer is a time-based trigger, rather than waiting for the completion of the previous callback method execution.
  • System.Threading.Timer does not run on the UI thread, so UI elements cannot be modified directly.
  • To modify a UI element in System.Threading.Timer, you can use the Invoke method of the UI element to achieve cross-thread access to the UI element.

Common properties:

  • DueTime: Gets or sets the delay time (in milliseconds) for the first triggering of the timer.
  • Period: Gets or sets the time interval (in milliseconds) for the timer to fire.

Commonly used methods:

  • Change(int dueTime, int period): Change the trigger time and interval of the timer.
  • Dispose(): Release the resources used by the timer and stop the timer.

Code example:

    public frmThreadingTimer()
    {
        InitializeComponent();
    }
    int count = 0;
    System.Threading.Timer threadTimer;
    private void frmThreadingTimer_Load(object sender, EventArgs e)
    {
        //多线程
        //period  时间间隔  0或-1 只会执行一 次,然后就停止
        //Change 可以让计时器重新启动
        //停止 period  0 -1   timer4.Dispose() 
        threadTimer = new System.Threading.Timer(new System.Threading.TimerCallback(oo => 
        {
            count += 1;
            Action<int> act = ChangeCount; //注册一个委托
            this.Invoke(act, count);
        }), null, 0, 1000);//第一个位置是一个回调函数
        //threadTimer.Change(2000, 2000);//改变延迟启动时间和时间间隔
    }
    private void ChangeCount(int count)
    {
        label1.Text = count.ToString();
        label2.Text = (count * 2).ToString();
        if (count > 10)
            threadTimer.Dispose();//计算十次后自动停止
    }
}

Insert image description here

[WinForm Detailed Tutorial] How to obtain source code

Insert image description here

[WinForm Detailed Tutorial 2] ComboBox, CheckedListBox, DateTimePicker, MonthCalender, and MaskedTextBox controls in WinForm
[WinForm Detailed Tutorial 1] Form, Label, TextBox, and Button in WinForm Control, RadioButton and CheckBox, ListBox

[Advanced C#] Summary of some common knowledge points in C# grammar
I hope it will be helpful, and you are welcome to follow me. More related content will be updated later!

おすすめ

転載: blog.csdn.net/QH2107/article/details/134100572