让软件有记忆功能
借助注册表ddl实现
1.导入注册表库&定义全局变量
public partial class Form1 : Form{//导入注册表库[DllImport(\"kernel32\")]private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);//系统dll导入ini写函数[DllImport(\"kernel32\")]private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);//系统dll导入ini读函数//这都是全局变量string FileName = System.AppDomain.CurrentDomain.BaseDirectory + \"data.ini\"; //ini文件名 存放注册表位置的StringBuilder temp = new StringBuilder(255); //存放 读出ini的内容string CurrentPortName; //当前串口号
2.添加 窗口关闭处理函数
public Form1(){InitializeComponent();serialPort1.DataReceived += new SerialDataReceivedEventHandler(PortDataReceivedEvent); //串口数据接收事件System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false; //this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(Form1_FormClosing);//窗口关闭处理函数}
3.窗口关闭时保存 我们的设置
private void Form1_FormClosing(object sender,EventArgs e) //窗口关闭时保存 我们的设置{WritePrivateProfileString(\"PortData\", \"PortName\", CurrentPortName, FileName);//窗口关闭,保存//********************要存到的数据块、要存到的key、要存的内容(当前串口号)、存放的地方(文件地址)***************************}
4.载入上次的设置
private void Form1_Load(object sender, EventArgs e) //载入上次的设置{this.Size = new Size(620, 107);//缩小GetPrivateProfileString(\"PortData\", \"PortName\", \"COM1\", temp, 256, FileName);//读取ini值,默认是COM1//******************要读的数据块、要读的key、为空默认的输出值、读取内容的存放变量、读取长度、要从FileName读取***********comboBox1.Text = temp.ToString();//初始化}