一. 事件处理
我们如何看到一个控件的事件?
- 在控件上右键,属性
- 切换到事件选项卡
- 输入想要触发的 回调函数名. (函数如果没有创建,回车会帮您创建)
二. 用代码添加事件处理
- 创造一个回调函数
private void testButton_Click(object sender, EventArgs e)
{
Console.WriteLine("haha!!!");
}
- 将回调函数添加到控件的事件中(这一步可以在事件面板中做,,也可以在构造函数中做)
testButton.Click += new EventHandler(this.testButton_Click); //添加了 事件句柄,并传入了回调事件
三. 弹出消息框
MessageBox.Show("这是一个弹出的消息框!");
四. 显示时间
- 显示当前时间
DateTime.Now.ToString("yyyy年MM月dd日 hh:mm:ss");
五. 窗体跳转
首先创建一个窗口,
然后把窗口实例化, 然后调用窗口实例的ShowDialog()方法跳转.
private void button1_Click(object sender, EventArgs e)
{
FromReg fromReg = new FromReg();
fromReg.ShowDialog();
}
六. 不同窗体间的控件公用
可以把控件的Modifiers属性改为public ,使之成为公共控件
image.png
再其他窗体中可使用 窗体名.控件名
来访问此控件
七. 关闭窗体/隐藏窗体
关闭自己窗体
this.Close();
关闭其他窗体
窗体名.Close()
隐藏窗体
this.Hidden();
八. 引用文件
如果我们访问与exe文件同目录的文件时, 可以使用相对路径写法
如果想要全路径
string tpath = "1.jpg"; //相对路径
string path = AppDomain.CurrentDomain.BaseDirectory + tpath; //绝对路径
PictureBox1.Image = Image.FromFile(path);
九. 获取枚举值
string[] s = Enum.GetNames(typeof(PictureBoxSizeMode));
十. 将index转化回枚举
PictureBox1.SizeMode = (PictureBoxSizeMode) indexNum
如下例:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp5
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
var s = Enum.GetNames(typeof(PictureBoxSizeMode));
comboBox1.Items.AddRange(s);
}
private void File_BTN_Click(object sender, EventArgs e)
{
OpenFileDialog1.ShowDialog();
}
private void OpenFileDialog1_FileOk(object sender, CancelEventArgs e)
{
textBox1.Text = OpenFileDialog1.FileName;
PictureBox1.Image = Image.FromFile(OpenFileDialog1.FileName);
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
var kk = comboBox1.SelectedIndex;
PictureBox1.SizeMode = (PictureBoxSizeMode) kk;
}
}
}
十一. DateTime类型可以运算
DateTime t1 = dateTimePicker1.Value;
DateTime t2 = dateTimePicker2.Value;
//直接运算, 并不完全可靠
TimeSpan tx1 = t2 - t1;
bool test1 = t2 > t1;
bool isequal1 = (t1 == t2);
Console.WriteLine(tx1);
Console.WriteLine(test1);
Console.WriteLine(isequal1);
//用内部方法运算
TimeSpan tx2 = t2.Subtract(t1);
int test2 = t2.CompareTo(t1); //早于显示负值,等于显示0, 晚于显示正值
bool isequal2 = t2.Equals(t1);
Console.WriteLine(tx2);
Console.WriteLine(test2);
Console.WriteLine(isequal2);