using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Windows.Forms; namespace System.Windows.Forms { /// /// /// public static class ControlExtension { //private static NLog.ILogger log = NLog.LogManager.GetLogger("ControlExtension"); /// /// 控件跨线程访问 /// /// /// /// /// public static void SafeInvoke(this Control uiElement, Action updater, bool forceSynchronous = true,bool isOutputLog=true) { try { if (uiElement == null) { throw new ArgumentNullException("uiElement"); } if (uiElement.InvokeRequired) { if (forceSynchronous) { uiElement.Invoke((Action)delegate { SafeInvoke(uiElement, updater, forceSynchronous); }); } else { uiElement.BeginInvoke((Action)delegate { SafeInvoke(uiElement, updater, forceSynchronous); }); } } else { if (uiElement.IsDisposed) { return; throw new ObjectDisposedException("Control is already disposed."); } updater(); } } catch (Exception ex) { if (isOutputLog) { //log.Error(ex); } } } /// /// 控件跨线程访问 /// /// /// /// /// /// /// public static void SafeInvoke(this Control uiElement, Action updater, T data, bool forceSynchronous = true, bool isOutputLog = true) { try { if (uiElement == null) { throw new ArgumentNullException("uiElement"); } if (uiElement.InvokeRequired) { if (forceSynchronous) { uiElement.Invoke(updater, data); } else { uiElement.BeginInvoke(updater, data); } } else { if (uiElement.IsDisposed) { return; throw new ObjectDisposedException("Control is already disposed."); } updater(data); } } catch (Exception ex) { if (isOutputLog) { //log.Error(ex); } } } /// /// 自动禁止启动执行 /// /// /// /// public static void SafeEnabledInvoke(this ToolStripItem uiElement, Action updater, string hintText = "正在执行.") { string value = uiElement.Text; uiElement.Enabled = false; uiElement.Text = hintText; try { updater(); } catch (Exception ex) { //log.Error(ex); } uiElement.Text = value; uiElement.Enabled = true; } /// /// 自动禁止启动控件执行 /// /// /// /// public static void SafeEnabledInvoke(this Control uiElement, Action updater,string hintText= "正在执行.") { uiElement.Enabled = false; string value = uiElement.Text; uiElement.Text = hintText; try { updater(); } catch (Exception ex) { //log.Error(ex); } uiElement.Text = value; uiElement.Enabled = true; } } }