C#常用经典代码片段

转载请注明出处:https://blog.csdn.net/Leytton/article/details/88891616
本文主要记录项目中经常需要查阅的C#代码片段。

0x01 子线程操作UI

以此处以label控件为例,其他控件同理。

label_控件.Invoke(new EventHandler(delegate{
        label_控件.Text = "更改控件属性";
}));

0x02 保存与读取二进制序列化文件

1、保存

string ConfigPath=AppDomain.CurrentDomain.BaseDirectory+"/config.bin";
AppConfig appConfig=new AppConfig();//自定义类
using (FileStream fs = new FileStream(ConfigPath, FileMode.Create))
{
     BinaryFormatter bf = new BinaryFormatter();
     bf.Serialize(fs, appConfig);
     fs.Close();
 }

2、读取


if (System.IO.File.Exists(ConfigPath)) {
      try
      {
          using (FileStream fs = new FileStream(ConfigPath, FileMode.Open))
          {
              BinaryFormatter bf = new BinaryFormatter();
              appConfig = (AppConfig)bf.Deserialize(fs);
              fs.Close();
          }
      }
      catch (Exception ex)
      {
          MessageBox.Show("配置文件读取错误,将用默认配置!", "错误");
      }
}

0x03 开机自启动

1、设置

//MessageBox.Show("设置开机自启动,需要修改注册表", "提示");
 string path = Application.ExecutablePath;
 RegistryKey rk = Registry.CurrentUser; //添加到 当前登陆用户的 注册表启动项
 try
 {
     //SetValue:存储值的名称
     RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
     rk2.SetValue("ProcessWatcher", path);
     rk2.Close();
     rk.Close();
     MessageBox.Show("设置开机自启动成功");
 }
 catch (Exception ex)
 {
     MessageBox.Show(ex.Message.ToString(), "提 示", MessageBoxButtons.OK, MessageBoxIcon.Error);
 }

注:程序运行路径不能包含特殊符号,否则路径会出现偏差导致无法开机启动的问题。
由于包含#符号,导致路径中的\,变成了/,这是不正常的。如下图:
在这里插入图片描述

2、取消

string path = Application.ExecutablePath;
RegistryKey rk = Registry.CurrentUser;
try
{
    RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
    rk2.DeleteValue("ProcessWatcher", false);
    rk2.Close();
    rk.Close(); 
    MessageBox.Show("已取消开机自启动");
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message.ToString(), "提 示", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
发布了154 篇原创文章 · 获赞 349 · 访问量 71万+

猜你喜欢

转载自blog.csdn.net/Leytton/article/details/88891616