old_flsystem/FLSystem/ControlExtension.cs

151 lines
4.5 KiB
C#

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace System.Windows.Forms
{
/// <summary>
///
/// </summary>
public static class ControlExtension
{
/// <summary>
/// 控件跨线程访问
/// </summary>
/// <param name="uiElement"></param>
/// <param name="updater"></param>
/// <param name="forceSynchronous"></param>
/// <param name="isOutputLog"></param>
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, true); });
}
else
{
uiElement.BeginInvoke((Action)delegate { SafeInvoke(uiElement, updater, false); });
}
}
else
{
if (uiElement.IsDisposed)
{
return;
throw new ObjectDisposedException("Control is already disposed.");
}
updater();
}
}
catch (Exception ex)
{
if (isOutputLog)
{
}
}
}
/// <summary>
/// 控件跨线程访问
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="uiElement"></param>
/// <param name="updater"></param>
/// <param name="data"></param>
/// <param name="forceSynchronous"></param>
/// <param name="isOutputLog"></param>
public static void SafeInvoke<T>(this Control uiElement, Action<T> 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)
{
}
}
}
/// <summary>
/// 自动禁止启动执行
/// </summary>
/// <param name="uiElement"></param>
/// <param name="updater"></param>
/// <param name="hintText"></param>
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)
{
}
uiElement.Text = value;
uiElement.Enabled = true;
}
/// <summary>
/// 自动禁止启动控件执行
/// </summary>
/// <param name="uiElement"></param>
/// <param name="updater"></param>
/// <param name="hintText"></param>
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)
{
}
uiElement.Text = value;
uiElement.Enabled = true;
}
}
}