c# 笔记

namespace System.Windows.Forms {
	public partial class ListViewEx : ListView {
		public ListViewEx() {
			SetStyle(ControlStyles.DoubleBuffer | ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);
			UpdateStyles();
		}
	}
}
  • 读写配置文件
using System.Configuration;
private static Configuration _conf = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
/// <summary>
/// 获取节点值
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="defaultVal"></param>
/// <returns></returns>
private static T GetNodeValue<T>(string key, T defaultVal) {
	var settings = _conf.AppSettings.Settings;
	var val = settings[key];
	var rv = defaultVal;
	if(val != null) {
		try {
			rv = (T)Convert.ChangeType(val.Value, typeof(T));
		} catch(Exception ex) {

		}
	}
	return rv;
}
/// <summary>
/// 设置节点值
/// </summary>
/// <param name="key"></param>
/// <param name="val"></param>
private static void SetNodeValue(string key, object val) {
	var settings = _conf.AppSettings.Settings;
	if(settings[key] == null) {
		settings.Add(key, val.ToString());
	} else {
		settings[key].Value = val.ToString();
	}
}
  • 程序仅运行一次
static class Program {
	static Mutex _mutex;
	/// <summary>
	/// 应用程序的主入口点。
	/// </summary>
	[STAThread]
	static void Main() {
		Application.EnableVisualStyles();
		Application.SetCompatibleTextRenderingDefault(false);
		//是否打开新进程
		bool createNew;
		// 获取程序集的Guid作为唯一标识
		Attribute attr = Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(), typeof(GuidAttribute));
		string guid = ((GuidAttribute)attr).Value;
		_mutex = new Mutex(true, guid, out createNew);
		if (createNew) {
			Application.Run(new FrmMain());
		} else {
			MessageBox.Show("程序已在运行中", Application.ProductName);
		}			
	}
}
  • 跨线程访问控件
/// <summary>
/// 跨线程访问控件的委托
/// </summary>
public delegate void CrossThreadCallHandler();
/// <summary>
/// 跨线程访问控件, 在控件上执行委托
/// </summary>
/// <param name="control">控件</param>
/// <param name="handler">执行的委托</param>
public static void CrossThreadCall(Control control, CrossThreadCallHandler handler) {
	if (control.InvokeRequired) {
		while (!control.IsHandleCreated) {
			if (control.Disposing || control.IsDisposed) {
				return;
			}						
		}
		//control.Invoke(handler);
		//IAsyncResult result = control.BeginInvoke(handler);
		//获取委托执行结果的返回值
		//control.EndInvoke(result);
		control.EndInvoke(control.BeginInvoke(handler));
	} else {
		handler();
	}
}
原文地址:https://www.cnblogs.com/zh33gl/p/10413725.html