ini檔為windows內常用來儲存setting的檔案,C#範例如下。
dllimport為必須要的,會動態連結到system32的檔案,
WritePrivateProfileString(string section, string key, string val, string filePath)寫入ini檔案
GetPrivateProfileString( string lpAppName, string lpKeyName, string lpDefault, StringBuilder lpReturnedString,uint nSize, string lpFileName)讀取ini檔案
P.S.此範例為自動抓取RS-232 port放入comboBox1內,尚未寫完,但讀寫ini的部分是完整的
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.IO.Ports;
namespace Test_INI
{
public partial class Form1 : Form
{
[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 Form1()
{
InitializeComponent();
string[] port_list = SerialPort.GetPortNames();
foreach (string port in port_list)
{
//MessageBox.Show("本機可用serial port: " + port); //測試用
comboBox1.Items.Add(port);
}
//當select port index換的時候 ,加入WritePrivateProfileString("Port Name", "name", 選擇的port
//string, @"D:\myConfig.ini");//寫入ini檔
WritePrivateProfileString("Port Name", "name", "COM1", @"D:\myConfig.ini");//寫入ini檔
WritePrivateProfileString("ModBus", "number", "1", @"D:\myConfig.ini");//寫入ini檔
WritePrivateProfileString("ModBus", "number", "2", @"D:\myConfig.ini");//寫入ini檔
}
private void button1_Click(object sender, EventArgs e)
{
StringBuilder data = new StringBuilder(255);
GetPrivateProfileString("Port Name", "name", "NA", data, 255,
@"D:\myConfig.ini");//section/key/def/ stringbuilder的變數/長度/路徑
MessageBox.Show(data.ToString());
}
}
}
2014年2月6日 星期四
[C#/winform] 不同解析度調整視窗大小
利用DPI取得螢幕解析度比例,進而改變WinForm的大小
廢話不多說
如上,DPI可能為
DPI | 大小百分比 |
96 | 100% |
120 | 125% |
144 | 150% |
廢話不多說
// 找出字體大小,並算出比例
float dpiX, dpiY;
Graphics graphics = this.CreateGraphics();
dpiX = graphics.DpiX;
dpiY = graphics.DpiY;
int intPercent = (dpiX == 96) ? 100 : (dpiX == 120) ? 125 : 150;
// 針對字體變更Form的大小
this.Height = this.Height * intPercent / 100;
this.Width = this.Width * intPercent / 100;
end.
位置:
台灣
訂閱:
文章 (Atom)