コード例 #1
0
 public static void RunOnUIThread(System.Windows.Forms.Control control, UIHelper.Action action)
 {
     if (UIHelper.obj == null)
     {
         if (control != null && control.InvokeRequired)
         {
             control.Invoke((Delegate)action);
         }
         else
         {
             if (action == null)
             {
                 return;
             }
             action();
         }
     }
     else
     {
         if (control == null || !control.InvokeRequired)
         {
             return;
         }
         object obj = UIHelper.obj((Delegate)action, new object[0]);
     }
 }
コード例 #2
0
 /// <summary>
 /// 跨线程改变控件的text
 /// </summary>
 /// <param name="btn"></param>
 /// <param name="value"></param>
 public static void ChangeBtnValue(System.Windows.Forms.Control control, string value)
 {
     try
     {
         //List<int> list = null;
         //list.Clear();
         if (control.InvokeRequired)//当是不同的线程在访问时为true,所以这里是true
         {
             InvokeChangeBtnValue invoke = new InvokeChangeBtnValue(ChangeBtnValue);
             control.Invoke(invoke, new object[] { control, value });
         }
         else
         {
             lock (control)
             {
                 if (control is System.Windows.Forms.TextBox)
                 {
                     System.Windows.Forms.TextBox txt = (System.Windows.Forms.TextBox)control;
                     txt.AppendText(value + "\r\n");
                     return;
                 }
                 control.Text = value;
             }
         }
     }
     catch (Exception ex)
     {
         LogHelper.WriteLog(ex.Message, ex);
     }
 }
コード例 #3
0
        public static object InvokeProperty(System.Windows.Forms.Control obj, string propertyName, params object[] paramValues)
        {
            Delegate del = null;
            string   key = obj.GetType().Name + "." + propertyName;
            Type     tp;

            lock (methodLookup)
            {
                if (methodLookup.Contains(key))
                {
                    tp = (Type)methodLookup[key];
                }
                else
                {
                    Type[] paramList = new Type[obj.GetType().GetProperty(propertyName).GetSetMethod().GetParameters().Length];
                    int    n         = 0;
                    foreach (ParameterInfo pi in obj.GetType().GetProperty(propertyName).GetSetMethod().GetParameters())
                    {
                        paramList[n++] = pi.ParameterType;
                    }
                    TypeBuilder        typeB = builder.DefineType("Del_" + obj.GetType().Name + "_" + propertyName, TypeAttributes.Class | TypeAttributes.AutoLayout | TypeAttributes.Public | TypeAttributes.Sealed, typeof(MulticastDelegate), PackingSize.Unspecified);
                    ConstructorBuilder conB  = typeB.DefineConstructor(MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName, CallingConventions.Standard, new Type[] { typeof(object), typeof(IntPtr) });
                    conB.SetImplementationFlags(MethodImplAttributes.Runtime);
                    MethodBuilder mb = typeB.DefineMethod("Invoke", MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig, obj.GetType().GetProperty(propertyName).GetSetMethod().ReturnType, paramList);
                    mb.SetImplementationFlags(MethodImplAttributes.Runtime);
                    tp = typeB.CreateType();
                    methodLookup.Add(key, tp);
                }
            }

            del = MulticastDelegate.CreateDelegate(tp, obj, obj.GetType().GetProperty(propertyName).GetSetMethod().Name);
            return(obj.Invoke(del, paramValues));
        }
コード例 #4
0
            static private void ListenHandler()
            {
                var myIP        = Communication.GetLocalIP();
                var epLocal     = new System.Net.IPEndPoint(myIP, TCPPort);
                var tcpListener = new System.Net.Sockets.TcpListener(epLocal);

                tcpListener.Start();

                while (IsListening)
                {
                    System.Threading.Thread.Sleep(1000);
                    if (tcpListener.Pending())
                    {
                        var tcpClient = tcpListener.AcceptTcpClient();
                        var netStream = tcpClient.GetStream();
                        var buffer    = new byte[1024];
                        if (!netStream.DataAvailable)
                        {
                            continue;
                        }

                        List <byte> bufferTotal = new List <byte>();
                        while (netStream.DataAvailable)
                        {
                            netStream.Read(buffer, 0, 1024);
                            bufferTotal.AddRange(buffer);
                        }
                        tcpClient.Close();
                        netStream.Close();
                        var receive = System.Text.Encoding.UTF8.GetString(bufferTotal.ToArray());
                        Owner.Invoke(DgGetMsg, receive);
                    }
                }
                tcpListener.Stop();
            }
コード例 #5
0
        /// <summary>
        /// 开始一个异步任务(用于界面UI)
        /// </summary>
        /// <param name="taskAction">异步任务执行委托</param>
        /// <param name="taskEndAction">异步任务执行完毕后的委托(会跳转回UI线程)</param>
        /// <param name="control">UI线程的控件</param>
        public void StartAsyncTask(Action taskAction, Action taskEndAction, System.Windows.Forms.Control control)
        {
            if (control == null)
            {
                return;
            }

            Task task = new Task(() => {
                try
                {
                    taskAction();

                    //返回UI线程
                    control.Invoke(new Action(() =>
                    {
                        taskEndAction();
                    }));
                }
                catch (Exception e)
                {
                    System.Windows.Forms.MessageBox.Show(e.Message);
                }
            });

            task.Start();
        }
コード例 #6
0
        protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
        {
            // Be nice - use BlockReentrancy like MSDN said
            using (BlockReentrancy()) {
                if (collectionChanged != null)
                {
                    Delegate[] delegates = collectionChanged.GetInvocationList();

                    // Walk thru invocation list
                    foreach (NotifyCollectionChangedEventHandler handler in delegates)
                    {
                        System.Windows.Forms.Control dispatcherObject = handler.Target as System.Windows.Forms.Control;

                        // If the subscriber is a DispatcherObject and different thread
                        if (dispatcherObject != null && dispatcherObject.InvokeRequired)
                        {
                            // Invoke handler in the target dispatcher's thread
                            dispatcherObject.Invoke(handler, this, e);
                        }
                        else   // Execute handler as is
                        {
                            collectionChanged(this, e);
                        }
                    }
                }
            }
        }
コード例 #7
0
        private void InvokeHandler(MulticastDelegate handlerList, EventArgs e)
        {
            if (handlerList == null)
            {
                return;
            }

            object[] args = new object[] { e };
            foreach (Delegate handler in handlerList.GetInvocationList())
            {
                object target = handler.Target;
                System.Windows.Forms.Control control
                    = target as System.Windows.Forms.Control;
                try
                {
                    if (control != null && control.InvokeRequired)
                    {
                        control.Invoke(handler, args);
                    }
                    else
                    {
                        handler.Method.Invoke(target, args);
                    }
                }
                catch (Exception ex)
                {
                    // TODO: Stop rethrowing this since it goes back to the
                    // Test domain which may not know how to handle it!!!
                    Console.WriteLine("Exception:");
                    Console.WriteLine(ex);
                    //throw new TestEventInvocationException( ex );
                    //throw;
                }
            }
        }
コード例 #8
0
        public static object GetControlInfo(System.Windows.Forms.Control control, string Info)
        {
            object value = null;

            if (control.InvokeRequired)
            {
                value = control.Invoke(new GetControlInfoHandle(GetControlInfo), control, Info);
            }
            else
            {
                foreach (PropertyInfo pi in typeof(System.Windows.Forms.Control).GetProperties())
                {
                    if (pi.Name.ToUpper() == Info.ToUpper())
                    {
                        return(pi.GetValue(control, null));
                    }
                }
                foreach (FieldInfo fi in typeof(System.Windows.Forms.Control).GetFields())
                {
                    if (fi.Name.ToUpper() == Info.ToUpper())
                    {
                        return(fi.GetValue(control));
                    }
                }
            }
            return(value);
        }
コード例 #9
0
 public static void SetControlInfo(System.Windows.Forms.Control control, string Info, object value)
 {
     if (control.InvokeRequired)
     {
         control.Invoke(new SetControlInfoHandle(SetControlInfo), control, Info, value);
     }
     else
     {
         foreach (PropertyInfo pi in typeof(System.Windows.Forms.Control).GetProperties())
         {
             if (pi.Name.ToUpper() == Info.ToUpper())
             {
                 pi.SetValue(control, value, null);
                 return;
             }
         }
         foreach (FieldInfo fi in typeof(System.Windows.Forms.Control).GetFields())
         {
             if (fi.Name.ToUpper() == Info.ToUpper())
             {
                 fi.SetValue(control, value);
                 return;
             }
         }
     }
 }
コード例 #10
0
ファイル: Log.cs プロジェクト: makicombi/autowebagent
        public void Write(string text)
        {
            string msg = string.Format("[{0}]\t{1}\r\n", DateTime.Now.ToString(), text);

            switch (stype)
            {
            case SinkType.CONTROL:

                if (control.InvokeRequired)
                {
                    control.Invoke(new System.Windows.Forms.MethodInvoker(delegate() { control.Text += msg; }));
                }
                else
                {
                    control.Text += msg;
                }
                break;

            case SinkType.FILE:
                file.AppendText().WriteLine(msg);
                break;

            case SinkType.EVENTLOG:
                eventLog.WriteEntry(msg);
                break;

            default:
                break;
            }
        }
コード例 #11
0
 /// <summary>
 /// Выполняет метод в главном потоке
 /// </summary>
 /// <param name="context">Контекст потока</param>
 /// <param name="action">Метод для выполнения</param>
 public static void RunUIContext(this System.Windows.Forms.Control context, Action action)
 {
     if (action == null)
     {
         throw new ArgumentNullException("action");
     }
     if (context == null)
     {
         throw new ArgumentNullException("context");
     }
     if (context.InvokeRequired)
     {
         try
         {
             context.Invoke(action);
         }
         catch (ObjectDisposedException e)
         {
             Debug.WriteLine(e.Message);
         }
     }
     else
     {
         action();
     }
 }
コード例 #12
0
        static public void ShowError(System.Windows.Forms.IWin32Window owner, Exception Ex)
        {
            try
            {
                System.Diagnostics.Debug.WriteLine(Ex.ToString());
            }
            catch
            {
            }
            //Save error to the last error log.
            //Vista: C:\ProgramData
            //XP: c:\Program Files\Common Files
            string path = string.Empty;

            //XP = 5.1 & Vista = 6.0
            if (Environment.OSVersion.Platform == PlatformID.Unix)
            {
                path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
                path = System.IO.Path.Combine(path, ".Gurux");
            }
            else
            {
                if (Environment.OSVersion.Version.Major >= 6)
                {
                    path = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
                }
                else
                {
                    path = Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFiles);
                }
                path = System.IO.Path.Combine(path, "Gurux");
            }
            path = System.IO.Path.Combine(path, "GXDLMSDirector");
            if (!System.IO.Directory.Exists(path))
            {
                System.IO.Directory.CreateDirectory(path);
            }
            path = System.IO.Path.Combine(path, "LastError.log");
            System.IO.TextWriter tw = System.IO.File.CreateText(path);
            tw.Write(Ex.ToString());
            tw.Close();
            System.Windows.Forms.Control ctrl = owner as System.Windows.Forms.Control;
            if (ctrl != null && !ctrl.IsDisposed && ctrl.InvokeRequired)
            {
                ctrl.Invoke(new ShowErrorEventHandler(OnShowError), owner, Ex);
            }
            else
            {
                if (ctrl != null && ctrl.IsDisposed)
                {
                    System.Windows.Forms.MessageBox.Show(Ex.Message, "Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                }
                else
                {
                    System.Windows.Forms.MessageBox.Show(owner, Ex.Message, "Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                }
            }
        }
コード例 #13
0
ファイル: Helpers.cs プロジェクト: xenoinc/ToolsHub
        /// <summary>
        ///   Execute on UI thread synchronously (waiting for completion before continuing).
        ///   Use this if we're reading back data from GUI thread, like text or something.
        /// </summary>
        /// <param name="control">Parent</param>
        /// <param name="code">Code to execute</param>
        /// <example>
        ///   Store.ExecuteThread(this, () =>
        ///   {
        ///     string getText = Text1.Text;
        ///   });
        /// </example>
        public static void ExecuteThreadInvoke(this System.Windows.Forms.Control control, Action code)
        {
            if (control.InvokeRequired)
            {
                control.Invoke(code);
                return;
            }

            code.Invoke();
        }
コード例 #14
0
        public bool Send(byte[] data)
        {
            bool rt = false;
            int  errorCode = 0; string errorMsg = "发送成功";

            try
            {
                if ((ISocket == null) || (!ISocket.Connected))
                {
                    errorCode = 1;
                    if (ISocket == null)
                    {
                        errorMsg = "Socket对象为空";
                        errorMsg = string.Format("服务器:[{0}]{1}", ISocket.RemoteEndPoint, errorMsg);
                    }
                    if (!ISocket.Connected)
                    {
                        errorMsg = "Socket对象未连接";
                        errorMsg = string.Format("服务器:[{0}]{1}", SktProperty.IP + ":" + SktProperty.Port, errorMsg);
                    }
                    return(rt);
                }

                int rint = ISocket.Send(data, data.Length, System.Net.Sockets.SocketFlags.None);
                rt = true;
            }
            catch (Exception ex)
            {
                Close();
                SktProperty.IsConnected = false; //改变连接属性

                errorCode = 1;
                errorMsg  = string.Format("服务器[{0}]{1}", ISocket.RemoteEndPoint, ex.Message);
                if (ClosedEvt != null)
                {
                    System.Windows.Forms.Control target = ClosedEvt.Target as System.Windows.Forms.Control;
                    errorCode = 1;
                    errorMsg  = string.Format("服务器[{0}]{1}", ISocket.RemoteEndPoint, ex.Message);
                    if (target != null && target.InvokeRequired)
                    {
                        //非创建控件线程同步调用事件:SocketClosed
                        target.Invoke(ClosedEvt, new object[] { errorCode, errorMsg });
                    }
                    else
                    {
                        //创建控件线程调用事件
                        ClosedEvt(SktProperty, errorCode, errorMsg);
                    }
                }
            }
            finally
            {
            }
            return(rt);
        }
コード例 #15
0
ファイル: ControlExtension.cs プロジェクト: qq5013/HK_NewLab
 /// <summary>
 /// 跨线程设置控件文本
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="value"></param>
 public static void SetText(this System.Windows.Forms.Control sender, string value)
 {
     if (sender.InvokeRequired)
     {
         sender.Invoke(new Action <System.Windows.Forms.Control, string>(SetText), sender, value);
     }
     else
     {
         sender.Text = value;
     }
 }
コード例 #16
0
ファイル: ControlExtension.cs プロジェクト: qq5013/HK_NewLab
 /// <summary>
 /// 跨线程设置控件背景颜色
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="value"></param>
 public static void SetBackColor(this System.Windows.Forms.Control sender, System.Drawing.Color value)
 {
     if (sender.InvokeRequired)
     {
         sender.Invoke(new Action <System.Windows.Forms.Control, System.Drawing.Color>(SetBackColor), sender, value);
     }
     else
     {
         sender.BackColor = value;
     }
 }
コード例 #17
0
ファイル: InvokeExtension.cs プロジェクト: crcruicai/Library
 /// <summary>
 /// 在拥有此控件的基础窗口句柄的线程上执行指定的委托。
 /// </summary>
 /// <param name="ctl"></param>
 /// <param name="doit"></param>
 public static void InvokeIfNeeded(this System.Windows.Forms.Control ctl, Action doit)
 {
     if (ctl.InvokeRequired)
     {
         ctl.Invoke(doit);
     }
     else
     {
         doit();
     }
 }
コード例 #18
0
ファイル: InvokeExtension.cs プロジェクト: crcruicai/Library
 /// <summary>
 /// 在拥有控件的基础窗口句柄的线程上,用指定的参数列表执行指定委托。
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="ctl"></param>
 /// <param name="doit"></param>
 /// <param name="arg1"></param>
 /// <param name="arg2"></param>
 public static void InvokeIfNeeded <T, S>(this System.Windows.Forms.Control ctl, Action <T, S> doit, T arg1, S arg2)
 {
     if (ctl.InvokeRequired)
     {
         ctl.Invoke(doit, arg1, arg2);
     }
     else
     {
         doit(arg1, arg2);
     }
 }
コード例 #19
0
ファイル: CTCC.cs プロジェクト: MeowthK/Youtube-DL-GUI
 public static void CrossThreadControlCall(System.Windows.Forms.Control control, System.Windows.Forms.MethodInvoker method)
 {
     if (control.InvokeRequired)
     {
         control.Invoke(method);
     }
     else
     {
         method.Invoke();
     }
 }
コード例 #20
0
        public bool Send(string strcmd)
        {
            bool rt = false;
            int  errorCode = 0; string errorMsg = "发送成功";

            try
            {
                if (ISerialPort == null || (!ISerialPort.IsOpen))
                {
                    errorCode = 1;
                    if (ISerialPort == null)
                    {
                        errorMsg = "SerialPort对象为空";
                        errorMsg = string.Format("串口:[{0}]{1}", ISerialPort.PortName, errorMsg);
                    }
                    if (!ISerialPort.IsOpen)
                    {
                        errorMsg = "SerialPort对象未连接";
                        errorMsg = string.Format("串口:[{0}]{1}", ISerialPort.PortName, errorMsg);
                    }
                    return(rt);
                }

                // Convert to byte array and send.
                byte[] cmdBuffer = Encoding.Default.GetBytes(strcmd);
                ISerialPort.Write(cmdBuffer, 0, cmdBuffer.Length);
                rt = true;
            }
            catch (Exception ex)
            {
                Close();
                Property.IsConnected = false;
                if (ClosedEvt != null)
                {
                    System.Windows.Forms.Control target = ClosedEvt.Target as System.Windows.Forms.Control;
                    errorCode = 1;
                    errorMsg  = string.Format("串口[{0}]{1}", ISerialPort.PortName, ex.Message);
                    if (target != null && target.InvokeRequired)
                    {
                        //非创建控件线程同步调用事件:SerialPortClosed
                        target.Invoke(ClosedEvt, new object[] { errorCode, errorMsg });
                    }
                    else
                    {
                        //创建控件线程调用事件
                        ClosedEvt(Property, errorCode, errorMsg);
                    }
                }
            }
            finally
            {
            }
            return(rt);
        }
コード例 #21
0
 public static void Invoke(System.Windows.Forms.Control Control, InvokeDelegate Delegate)
 {
     if (Control.InvokeRequired)
     {
         Control.Invoke(Delegate);
     }
     else
     {
         Delegate();
     }
 }
コード例 #22
0
ファイル: InvokeHelper.cs プロジェクト: CairoLee/svn-dump
 public static void Invoke(System.Windows.Forms.Control con, InvokeDelegate callback)
 {
     if (con.InvokeRequired)
     {
         con.Invoke(callback);
     }
     else
     {
         callback();
     }
 }
コード例 #23
0
 /// <summary>
 /// Invoke a delegate safely on a speficied control
 /// </summary>
 /// <param name="Action">The delegate to execute</param>
 /// <param name="owner">The control to execute on</param>fasdas
 /// <param name="args">The arguments to pass to the delegate</param>
 public static void SafeInvoke(this Delegate Action, System.Windows.Forms.Control owner, params object[] args)
 {
     if (owner.InvokeRequired)
     {
         owner.Invoke(Action, args);
     }
     else
     {
         Action.DynamicInvoke(args);
     }
 }
コード例 #24
0
ファイル: EditorService.cs プロジェクト: gleibson/phobos3d
 //Thread safe
 public static void ProcessMessage(string message)
 {
     if (m_invokeControl.InvokeRequired)
     {
         m_invokeControl.Invoke(new System.Windows.Forms.MethodInvoker(delegate { MainThreadProcessMessage(message); }));
     }
     else
     {
         MainThreadProcessMessage(message);
     }
 }
コード例 #25
0
ファイル: Form.cs プロジェクト: kyelbek/MobileRobots
        // TODO: ---> SafeInvoke
        // Dzięki tej metodzie jesteśmy w stanie edytować kontrolkę LogBOX z poziomu innego threadu (Timer1) niż ten, w którym została utworzona (Form) bez potencjalnych kolizji i nieprzewidzianych skutków
        // https://stackoverflow.com/questions/13345091/is-it-safe-just-to-set-checkforillegalcrossthreadcalls-to-false-to-avoid-cross-t
        // W przypadku tego programu nieprzewidziane skutki objawiały się jako przemieszane ze sobą dane "Sent: XX  Received: XX", np. "S   Received:XXent:XX"

        public static void SafeInvoke(System.Windows.Forms.Control control, System.Action action)
        {
            if (control.InvokeRequired)
            {
                control.Invoke(new System.Windows.Forms.MethodInvoker(() => { action(); }));
            }
            else
            {
                action();
            }
        }
コード例 #26
0
 public static void UpdateUI(this System.Windows.Forms.Control control, Action updateAction)
 {
     if (control.InvokeRequired)
     {
         control.BeginInvoke(updateAction);
     }
     else
     {
         control.Invoke(updateAction);
     }
 }
コード例 #27
0
 public void Invoke(System.Action action)
 {
     if (_threadControl.InvokeRequired)
     {
         _threadControl.Invoke(new SafeInvokeDelegate(Invoke), new object[] { action });
     }
     else if (action != null)
     {
         action();
     }
 }
コード例 #28
0
 public static void SetControlPropertyThreadSafe(System.Windows.Forms.Control control, string propertyName, object propertyValue)
 {
     if (control.InvokeRequired)
     {
         control.Invoke(new SetControlPropertyThreadSafeDelegate(SetControlPropertyThreadSafe), new object[] { control, propertyName, propertyValue });
     }
     else
     {
         control.GetType().InvokeMember(propertyName, System.Reflection.BindingFlags.SetProperty, null, control, new object[] { propertyValue });
     }
 }
コード例 #29
0
 /// <summary>
 /// Presses the enter.
 /// </summary>
 /// <param name="xControl">The x control.</param>
 public static void PressEnter(System.Windows.Forms.Control xControl)
 {
     if (xControl.InvokeRequired)
     {
         PressEnter_Delegate xFun = new PressEnter_Delegate(PressEnter);
         xControl.Invoke(xFun, new object[] { xControl });
         return;
     }
     xControl.Focus();
     System.Windows.Forms.SendKeys.SendWait("{ENTER}");
 }
コード例 #30
0
 public static void Invoke(this System.Windows.Forms.Control control, Action action)
 {
     if (control.InvokeRequired)
     {
         control.Invoke(new System.Windows.Forms.MethodInvoker(action), null);
     }
     else
     {
         action.Invoke();
     }
 }