using System;
using System.Windows.Forms;

namespace ChuPiao.Common.Utils
{
    public delegate TResult Func<T1, T2, TResult>(T1 arg1, T2 arg2);
    /// <summary>
    /// 工具类，在UI线程上进行调用,这样就可以对UI进行操作了
    /// </summary>
    public class UIThreadInvoker:ISafeInvoker
    {
        #region ISafeInvoker 成员

        public object SafeInvoke(Delegate method, params object[] args)
        {
            Form currentForm = null;

            if (Application.OpenForms.Count > 0)
            {
                currentForm = Application.OpenForms[0];
            }
            if (null != currentForm)
            {
                if (currentForm.InvokeRequired)
                {
                    try
                    {
                        return currentForm.Invoke(new Func<Delegate, object[], object>(SafeInvoke), method, args);
                    }
                    catch (Exception ex)
                    {
                        return null;
                    }
                }
                else
                {
                    return method.DynamicInvoke(args);
                }
            }
            else
            {
                try
                {
                    return method.DynamicInvoke(args);
                }
                catch (Exception ex)
                {
                    return null;
                }
            }
        }

        #endregion
    }
}
