熊爸的学习时间

WinForm入门(四) 杂乱知识点

2020-08-07  本文已影响0人  熊爸天下_56c7

一. 事件处理

我们如何看到一个控件的事件?

二. 用代码添加事件处理

        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);
上一篇 下一篇

猜你喜欢

热点阅读