文章

C# WinForm 实战:随机点号器

Gitee上:https://gitee.com/diyanqi07/RandomCallUp

概要

在本文中,笔者整理了以下内容:

  • 如何利用C#的随机数模块生成随机整数;
  • 如何.NET6.0的特性进行await延时;
  • 如何使用Tooltip
  • 利用技巧,让窗口内的所有元素都随窗口缩放;
  • 读/写json文件;
  • 限制文本框的输入为数字。

当然, 编程的生命在于复制粘贴 ,所以本文难免出现纰漏。笔者也不是专门学C#的,故小错误请大佬指出QWQ

正文

随机数

Random rd = new Random();//申明一个随机类
int rannumber = rd.Next(PublicValue.minnumber, PublicValue.maxnumber + 1);//生成随机数

warning 注意
Next函数中,第一个值是最小值(含),第二个值是最大值(不含)。

await特性

对于任何要使用await的函数,都应该在其外部申明子进程:

Task task = Task.Factory.StartNew(async () => //申明async
{
    //内部语句...
    for (double i = 0; i < PublicValue.loadtime; i += PublicValue.loaddelta)
    {
        await Task.Delay(100);
    }
});

但是,当您使用了Task子进程,您就无法直接访问源程序中的变量了。下面给出了解决方案:

Task task = Task.Factory.StartNew(async () => //申明async
{
    //内部语句...
    for (double i = 0; i < PublicValue.loadtime; i += PublicValue.loaddelta)
    {
        await Task.Delay(100);//await最大的作用莫过于使延时函数在执行语句块中真正延时生效了。这里的100单位是毫秒
        // do something...
    }
    //利用this.Invoke内部操作,直接访问源程序中的内容
    this.Invoke(new EventHandler(delegate
    {
        this.ranget.Text = "随机抽取!";
        this.ranget.Enabled = true;
        this.result.ForeColor = Color.Red;
    }));
});

warning 提示
await特性仅用于.NET6.0+。这意味着大部分平台都不能很好地兼容该特性,所以请谨慎使用。

Tooltip用法

ToolTip t = new ToolTip();//首先,创建一个ToolTip对象
//然后,设置该ToolTip的属性
t.ShowAlways = true;//是否显示
t.InitialDelay = 500;//多少时间后显示
t.AutoPopDelay = 0;//提示信息的可见时间
t.ReshowDelay = 500;//鼠标移动到另一个控件,间隔多少时间再显示

窗口内的元素全局缩放

#region 控件大小随窗体大小等比例缩放
        private float x;//定义当前窗体的宽度
        private float y;//定义当前窗体的高度
        private void setTag(Control cons)
        {
            foreach (Control con in cons.Controls)
            {
                con.Tag = con.Width + ";" + con.Height + ";" + con.Left + ";" + con.Top + ";" + con.Font.Size;
                if (con.Controls.Count > 0)
                {
                    setTag(con);
                }
            }
        }
        private void setControls(float newx, float newy, Control cons)
        {
            //遍历窗体中的控件,重新设置控件的值
            foreach (Control con in cons.Controls)
            {
                //获取控件的Tag属性值,并分割后存储字符串数组
                if (con.Tag != null)
                {
                    string[] mytag = con.Tag.ToString().Split(new char[] { ';' });
                    //根据窗体缩放的比例确定控件的值
                    con.Width = Convert.ToInt32(System.Convert.ToSingle(mytag[0]) * newx);//宽度
                    con.Height = Convert.ToInt32(System.Convert.ToSingle(mytag[1]) * newy);//高度
                    con.Left = Convert.ToInt32(System.Convert.ToSingle(mytag[2]) * newx);//左边距
                    con.Top = Convert.ToInt32(System.Convert.ToSingle(mytag[3]) * newy);//顶边距
                    int none;
                    Single currentSize;
                    if (!int.TryParse(this.result.Text, out none))
                    {
                        currentSize = (float)(System.Convert.ToSingle(mytag[4]) * newy*0.6);//字体大小
                    }
                    else
                    {
                        currentSize = (float)(System.Convert.ToSingle(mytag[4]) * newy);
                    }
                    //currentSize = ((float)((float) System.Convert.ToSingle(mytag[4]) * newy * 0.6));
                    con.Font = new Font(con.Font.Name, currentSize, con.Font.Style, con.Font.Unit);
                    if (con.Controls.Count > 0)
                    {
                        setControls(newx, newy, con);
                    }
                }
            }
        }
        private void Form1_Resize(object sender, EventArgs e)
        {
            float newx = (this.Width) / x;
            float newy = (this.Height) / y;
            setControls(newx, newy, this);
        }

        #endregion

提示:本段代码也是从某博客直接粘贴过来的,但原链接我忘记了……或许您可以告诉我真相((

读/写JSON文件

读json

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;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
public static string GetConnectionString(string value)
        {
            var configurationBuilder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("config.json");
            IConfiguration config = configurationBuilder.Build();
            string connectionString = config[value];
            return connectionString;
        }

//使用:
resultnum = GetConnectionString("maxnumber");
resultstr = GetConnectionString("maxstring");

对于上面的样例,我们假定有这样一个json文件:

{
    "maxnumber":123,
    "maxstring":"123"
}

那么,resultnum将会是数字类型的123resultstr将会是字符串类型的123

写json

写json的实质就是把json对象打包成字符串,然后储存字符串到文件即可。

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;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

                StreamReader reader = File.OpenText("config.json");
                JsonTextReader jsonTextReader = new JsonTextReader(reader);
                JObject jsonObject = (JObject)JToken.ReadFrom(jsonTextReader);
                jsonObject["minnumber"] = minnumber;
                jsonObject["maxnumber"] = maxnumber;
                reader.Close();
                string output = JsonConvert.SerializeObject(jsonObject, Formatting.Indented);
                File.WriteAllText("config.json", output);

限制文本框输入为数字

private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(e.KeyChar == '\b' || (e.KeyChar >= '0' && e.KeyChar <= '9')))
            {
                e.Handled = true;
            }
        }

如上,只允许退格、0~9。

本文由作者按照 CC BY 4.0 进行授权

© Dignite. 保留部分权利。 由  提供CDN加速。

浙ICP备2023032699号 | 使用 Jekyll 主题 Chirpy