Article directory
1.WinForm file structure
.sln文件
: Solution file location reference
bin文件夹
: Store the compilation results of the project exe dll debug debug release release pdb location information – debugging
obj文件夹
object during compilation The generated intermediate temporary file speeds up compilation
Properties
Reference Add reference--select the required assembly
App.config
Configuration file
.csproj
Project file location Reference double-click to open the project
Program.cs
:Program entry
Form.cs
Source code (window processing code)
Form.Designer.cs
Form layout code automatically generates corresponding control code
Form.resx
Form resources
2. Common properties, methods and events of forms
2.1 Commonly used attributes (can be set directly in the attributes)
Property name | describe | Sample code |
---|---|---|
Text |
Title of the form | this.Text = "My Application"; |
Size |
form size | this.Size = new Size(800, 600); |
Location |
The position of the form on the screen | this.Location = new Point(100, 100); |
WindowState |
The state of the form (normal, minimized, maximized) | this.WindowState = FormWindowState.Maximized; |
BackColor |
The background color of the form | this.BackColor = Color.Red; |
FormBorderStyle |
The style of the form border | this.FormBorderStyle = FormBorderStyle.FixedDialog; |
StartPosition |
The initial position of the form | this.StartPosition = FormStartPosition.CenterScreen; |
2.2 Common methods
method name | describe | Sample code |
---|---|---|
Show() |
show form | this.Show(); |
ShowDialog() |
ModalDisplay form | this.ShowDialog(); |
Hide() |
Hide form | this.Hide(); |
Close() |
close form | this.Close(); |
Activate() |
Activate form | this.Activate(); |
Invalidate() |
Force a form to be redrawn | this.Invalidate(); |
Show()
and ShowDialog()
are two different methods for displaying a form. The differences are as follows:
-
Show()
-
Non-modal form (Non-modal): When you use the
Show()
method to display a form, the user can freely Switch between the opened form and the original form. -
Parallel interaction: The user can interact with the parent form and child form at the same time.
-
Code execution continues: The code following the
Show()
method will be executed immediately and will not wait for the newly opened form to close.
-
-
ShowDialog()
-
Modal form (Modal): When you use
ShowDialog()
to open a form, the user must first close the form before continuing with Parent form interaction. -
Serial Interaction: The user cannot interact with the parent form until the new form is closed.
-
Code waits:
ShowDialog()
The following code will wait for the user to close the newly opened form before executing.
-
2.3 Common events
event name | describe | Example uses |
---|---|---|
Load |
Fires when form loads | Initialize form content |
Click |
Fires when clicked on the form | Handle click event |
MouseMove |
Triggered when the mouse moves on the form | Implement custom mouse tracking |
KeyPress |
Fires when a keyboard key is pressed | Handle keyboard input |
FormClosing |
Fires when the form is about to close | Pop up a confirmation dialog box or save settings |
Resize |
Triggered when the form size changes | Dynamically adjust control position and size |
3.Label, TextBox and Button controls
Label control:
- Attributes:
- Name: The name of the control, used to reference it in code, usually starts with lbl, for example: lblUserName
- Text: Set or get the text information displayed on the label.
- Image: used to display images.
- ImageList: Image set control.
- Size: The size of the control, including Width and Height.
- Tag: Custom data related to the control.
- Enabled: Determines whether the label is enabled.
- Location: The location of the control on the form, including X and Y coordinates.
- event:
- Click: Fires when the user clicks on the label.
- TextChanged: Fires when the text content of the label changes.
TextBox control:
- Attributes:
- Name: The name of the control. Generally starts with txt, for example: txtUserName
- Text: used to input and obtain text information.
- MultiLine: Determines whether the text box supports multi-line text input.
- WordWrap: Determines whether automatic word wrapping is possible.
- PasswordChar: Specifies the password character in the password box.
- Size: The size of the control.
- Enabled: Determines whether the text box is enabled.
- Location: The location of the control on the form.
- method:
- AppendText(text): Appends the specified text to the end of the text box.
- Clear(): Clear the text in the text box.
- Focus(): Make the text box gain focus.
- Select(): Select the text in the text box.
- SelectAll(): Select all text in the text box.
- event:
- TextChanged: Fires when the text content of the text box changes.
- Click: Generally not used for text boxes, usually used for controls such as buttons.
Button control:
- Attributes:
- Name: The name of the control.
- Text: The text used to display on the button.
- BackgroundImage: background image.
- Image: The image displayed on the button.
- BackColor: background color.
- ForeColor: text color.
- Visible: Determines whether the button is visible.
- event:
- Click: Triggered when the user clicks a button, usually used to execute button-related commands.
Case: Make a simple login interface
code
public partial class FrmUser : Form
{
public FrmUser()
{
InitializeComponent();
txtName.Text = "请输入账户";
txtPassword.Text = "请输入密码";
txtName.ForeColor = Color.Gray;
txtPassword.ForeColor = Color.Gray;
}
private void Form1_Load(object sender, EventArgs e) //sender事件触发的对象
{
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
txtPassword.ForeColor = Color.Black;
}
private void txtName_TextChanged(object sender, EventArgs e)
{
txtName.ForeColor = Color.Black;
}
private void button2_Click(object sender, EventArgs e)
{
string UserName = txtName.Text.Trim();
string userPwd = txtPassword.Text;
if (string.IsNullOrEmpty(UserName) || UserName == "请输入账户")
{
MessageBox.Show("请输入用户名!", "登录页面", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(userPwd) || UserName == "请输入密码")
{
MessageBox.Show("请输入密码!", "登录页面", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
MessageBox.Show("登录成功!", "进入主界面中....", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void btn_Click(object sender, EventArgs e)
{
this.Close();
}
}
The code implements a basic user login interface. The user can enter the user name and password, click the "Login" button to log in, or click the "Close" button to close the form. It also includes some user-friendly features, such as displaying prompt text in text boxes, changing text color when entering text, and displaying error message boxes during input validation.
4.RadioButton和CheckBox
RadioButton (radio button)
RadioButton
Used to select a single option from a set of options. In a group of radio buttons, only one of them can be selected, mutually exclusive.
Attribute:
Name
: the name of the controlText
: Text displayed on the interfaceChecked
: Whether it is selected, returns a Boolean valueAutoCheck
: Automatically change the selected state of other RadioButtons. The default is true.
incident:
CheckedChanged
: This event is triggered when the selected state changes.
Useful scene:
- Role selection login
- sex selection
Grouping and code operations: RadioButton controls are usually placed within a GroupBox control to form a logical grouping so that only one option can be selected in this grouping. The state of a RadioButton can also be easily changed through code, such as radioButton1.Checked = true;
.
Event handling: You can add logic in the event handler of the CheckedChanged
event to respond to user actions. For example:
csharpCopy codeprivate void radioButton1_CheckedChanged(object sender, EventArgs e)
{
if (radioButton1.Checked)
{
// 执行某些操作
}
}
CheckBox
CheckBox
Used to select one or more items from a set of options.
Attribute:
Name
: the name of the controlText
: Text displayed on the interfaceChecked
: Whether it is selected, returns a Boolean value.AutoCheck
: Automatically changes the selected state when clicked, the default is true, usually do not modify this property.CheckState
: Represents three different states - unselected, selected, and intermediate state.ThreeState
: Controls whether CheckBox has three states or two states. The default is false.
incident:
CheckedChanged
: Triggered whenChecked
attribute value changes.CheckStateChanged
: Fires whenCheckState
changes.
Event triggering sequence:
CheckedChanged
(Checked attribute value changes)CheckStateChanged
(CheckState changes)
Useful scene:
- Permission assignment
- Role Assignments
Advanced usage and code operation: When the ThreeState
attribute is set to true, CheckBox
can have three states: Unselected, selected and intermediate states. This may be useful in some complex scenarios (e.g. batch operations). The state of a CheckBox can also be easily changed through code, such as checkBox1.Checked = true;
or checkBox1.CheckState = CheckState.Indeterminate;
.
Event handling: You can add logic in the event handler of the CheckedChanged
or CheckStateChanged
event to respond User operations. For example:
csharpCopy codeprivate void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (checkBox1.Checked)
{
// 执行某些操作
}
}
Example:
public partial class frmSubmit : Form
{
public frmSubmit()
{
InitializeComponent();
}
private void btnCancel_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnOk_Click(object sender, EventArgs e)
{
MessageBox.Show("提交成功!", "提交完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void rdWriter_CheckedChanged(object sender, EventArgs e)
{
DialogResult result = MessageBox.Show("确定切换吗?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
// 判断用户的选择
if (result == DialogResult.OK)
{
// 用户选择了 OK,执行相应的操作
// 这里可以放置你想要执行的代码
}
else if (result == DialogResult.Cancel)
{
// 用户选择了 Cancel,可以选择不执行任何操作
// 或者放置一些取消操作的代码
}
}
}
The above code contains the processing logic for button click events and radio button selection events. As the user interacts with the form, it displays a message box to obtain confirmation or cancellation from the user and performs the appropriate action based on the user's selection.
5.ListBox (list box)
ListBox is a control in Windows Forms that displays a list of options from which the user can select one or more items.
Attribute:
Name
: the name of the controlItems
: A collection of items in a list box that allows you to add, remove, and manipulate items in the list.DataSource
: Data source, used to bind the ListBox to an external data source, usually used with theDisplayMember
andValueMember
properties.DisplayMember
: Specifies the name of the field displayed when binding the data source.ValueMember
: Specifies the name of the field to use as a value when binding the data source.
incident:
SelectedIndexChanged
: Event triggered when the selection changes. It can be used to capture the user's selection changes.
Example:
public partial class FrmListBox : Form
{
public FrmListBox()
{
InitializeComponent();
}
private void FrmListBox_Load(object sender, EventArgs e)
{
//项的清除
listBox1.Items.Clear();
//避免控件闪烁的问题
listBox1.BeginUpdate();//闪烁
//for循环等加载大量的项
listBox1.EndUpdate();
//添加项
listBox1.Items.Add(123);
listBox1.Items.Add("jason");
string[] list = { "adbc", "admin", "sqlserver" };
listBox1.Items.AddRange(list);
listBox1.Items.Insert(3, "micosoft");
int index = listBox1.Items.IndexOf("admin");//获取索引
bool bl = listBox1.Items.Contains("sqlserver");//存在
listBox1.Items.Remove("admin");
listBox1.Items.RemoveAt(3);
}
}
**Example 2:** Use the ListBox
control and perform data binding through a custom UserInfo
class.
List<UserInfo> userInfos = new List<UserInfo>();
userInfos.Add(new UserInfo()
{
ID = 1,
Name = "admin"
});
userInfos.Add(new UserInfo()
{
ID = 2,
Name = "lycchun"
});
userInfos.Add(new UserInfo()
{
ID = 3,
Name = "lwb"
});
userInfos.Add(new UserInfo()
{
ID = 4,
Name = "Eleven"
});
userInfos.Add(new UserInfo()
{
ID = 5,
Name = "Jason"
});
//绑定数据 项的实际值一般来说,就会指定对应显示值的编号
listBox1.DataSource = userInfos;//选项的来源
listBox1.DisplayMember = "Name";//项显示的文本对应属性名
listBox1.ValueMember = "ID";//项的实际值对应的属性名
//将对项集合的修改转换成对数据源集合的修改
List<UserInfo> listNew = listBox1.DataSource as List<UserInfo>;
listNew.Add(new UserInfo()
{
ID = 6,
Name = "adbc"
});
listNew.RemoveAt(2);
listBox1.DataSource = null;
listBox1.DataSource = listNew;
listBox1.DisplayMember = "Name";//项显示的文本对应属性名
listBox1.ValueMember = "ID";//项的实际值对应的属性名
//var indexes =listBox1.SelectedIndex;
//var items = listBox1.SelectedItem;
//int index = listBox1.SelectedValue;
//var item0 =listBox1.SelectedIndices;
//var val = listBox1.SelectedItems;
[WinForm Detailed Tutorial] How to obtain the source code:
Excellent recommendations:
[C# Advanced 1] Array (Array), collection (ArrayList, Queue, Stack, HashList), List
[C# Advanced 8] Serialization and deserialization in C# (binary serialization, XML serialization and JSON serialization) a>
[Advanced C#] Summary of some common knowledge points in C# syntax
[WinForm detailed tutorial 1] Form, Label, TextBox and Button controls, RadioButton and CheckBox, ListBox
[WinForm detailed tutorial three] NumericUpDown, PictureBox, RichTextBox and three Timer controls in WinForm
[WinForm detailed tutorial four] ProgressBar and ImageList in WinForm and ListView control
[WinForm detailed tutorial five] MenuStrip, ContextMenuStrip, ToolStrip, StatusStrip control in WinForm
[WinForm detailed tutorial six] GroupBox and Panel in WinForm , TabControl, SplitContainer control
[C# Advanced] Delegates, events, callback functions, anonymous functions and lambda expressions in C#
If you are interested in the intelligent construction major, or are a student, teacher or practitioner in a related field, you are welcome to join us through the WeChat public account [Intelligent Construction Xiaoshuo]!
Hope it helps, and welcome to follow us. More related content will be updated later!