在做软件插件的时候,经常需要记住用户输入的动作,这个时候最容易想到的是用静态字段来保存结果,但是静态字段处理不好,容易占用大量内存,还会导致意向不到的错误,如果用kernel32.dll这个文件来生成ini文件来保存中间参数,会方便很多。
一些简单介绍,请参考:
https://www.cnblogs.com/yuanyuan/archive/2010/12/08/1900191.html
下面看具体实例,我这里用wpf来展示这个功能:
1、Model类
public class Model
{
public int Value1 { get; set; }
public int Value2 { get; set; }
public int Value3 { get; set; }
public Model()
{
Value1 = 100;
Value2 = 101;
Value3 = 102;
}
}
2、kernel的用法:
public class Setting
{
public string FilePath { get; set;}
private const string parmSection = "Parameter";
private const string key1 = "a";
private const string key2 = "b";
private const string key3 = "c";
//声明读写INI文件的API函数
[DllImport("kernel32")]
private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
public Setting()
{
FilePath= System.Environment.CurrentDirectory+"\\Kernel.ini";
}
private void WriteInivalue(string Section, string Key, string value)
{
WritePrivateProfileString(Section, Key, value, this.FilePath);
}
private string ReadInivalue(string Section, string Key)
{
StringBuilder temp = new StringBuilder(255);
int i = GetPrivateProfileString(Section, Key, "", temp, 255, this.FilePath);
return temp.AppendLine().ToString();
}
public void Save(Model model)
{
WriteInivalue(parmSection, key1, model.Value1.ToString());
WriteInivalue(parmSection, key2, model.Value2.ToString());
WriteInivalue(parmSection, key3, model.Value3.ToString());
}
public Model Read()
{
Model model = new Model();
model.Value1 = int.Parse(ReadInivalue(parmSection, key1));
model.Value2 = int.Parse(ReadInivalue(parmSection, key2));
model.Value3 = int.Parse(ReadInivalue(parmSection, key3));
return model;
}
}
3、窗口:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
Model model = new Model();
Setting setting = new Setting();
setting.Save(model);
this.DataContext = setting.Read();
}
}
xaml代码:
<Grid>
<StackPanel>
<TextBox Text="{Binding Path=Value1}"></TextBox>
<TextBox Text="{Binding Path=Value2}"></TextBox>
<TextBox Text="{Binding Path=Value3}"></TextBox>
</StackPanel>
<TextBlock ></TextBlock>
</Grid>
最后结果: