BeginInvoke() private method

private BeginInvoke ( Delegate method ) : IAsyncResult
method System.Delegate
return IAsyncResult
Example #1
1
 /// <summary>
 /// 跨线程访问控件
 /// </summary>
 /// <param name="ctrl">Form对象</param>
 /// <param name="de">委托</param>
 public static void Invoke(Control ctrl, Delegate de)
 {
     if (ctrl.IsHandleCreated)
     {
         ctrl.BeginInvoke(de);
     }
 }
Example #2
1
 public static void BeginInvokeInControlThread(Control c, MethodInvoker code)
 {
     //c.BeginInvoke(code);
     if (c.InvokeRequired)
         c.BeginInvoke(code);
     else
         c.Invoke(code);
 }
Example #3
1
 private static void hider(Control frm)
 {
     frm.BeginInvoke((MethodInvoker)delegate
     {
         frm.Hide();
         load.Hide();
     });
 }
Example #4
0
 void Run()
 {
     System.Windows.Forms.Control tmp = Sender as System.Windows.Forms.Control;
     try
     {
         Command(Sender, this, Parameters);
         if (OnAsyncStateChangeEventHandler != null)
         {
             if (tmp != null && tmp.InvokeRequired)
             {
                 tmp.BeginInvoke(OnAsyncStateChangeEventHandler, Sender, this, Parameters, AsyncState.Finish, null);
             }
             else
             {
                 OnAsyncStateChangeEventHandler(Sender, this, Parameters, AsyncState.Finish, null);
             }
         }
     }
     catch (Exception ex)
     {
         if (OnError == null)
         {
             if (tmp != null && tmp.InvokeRequired)
             {
                 tmp.Invoke(new ErrorEventHandler(ShowError), Sender, ex);
             }
             else
             {
                 ShowError(Sender, ex);
             }
         }
         else
         {
             if (tmp != null && tmp.InvokeRequired)
             {
                 tmp.Invoke(new ErrorEventHandler(OnError), Sender, ex);
             }
             else
             {
                 OnError(Sender, ex);
             }
         }
         if (OnAsyncStateChangeEventHandler != null)
         {
             if (tmp != null && tmp.InvokeRequired)
             {
                 tmp.BeginInvoke(OnAsyncStateChangeEventHandler, Sender, this, Parameters, AsyncState.Finish, null);
             }
             else
             {
                 OnAsyncStateChangeEventHandler(Sender, this, Parameters, AsyncState.Finish, null);
             }
         }
     }
     finally
     {
         Done.Set();
     }
 }
 public void Go()
 {
     if (attachedLibrary == false)
     {
         control.BeginInvoke((Action)TimerGo, null);
     }
 }
Example #6
0
 private void InvokeOwnThread(Control control, Action action)
 {
     if (control.InvokeRequired)
         control.BeginInvoke(action);
     else
         action();
 }
Example #7
0
 /// <summary>
 /// Performs the action on the control by calling BeginInvoke, if it is required to do so
 /// </summary>
 /// <param name="control"></param>
 /// <param name="action"></param>
 public static void PerformControlOperation(Control control, NoParam action)
 {
     if (control.InvokeRequired)
         control.BeginInvoke(new InvokeDelegate(TryCatchInvoker), new Invoke(action, null));
     else
         TryCatchInvoker(new Invoke(action, null));
 }
Example #8
0
        /// <summary>
        /// Invokes asynchronously the specified action for this control.
        /// </summary>
        /// <param name="control">The control.</param>
        /// <param name="action">The action.</param>
        public static void BeginInvoke(Control control, Action action)
        {
            control.ThrowIfNull("control");
            action.ThrowIfNull("action");
            if (!control.Created || control.IsDisposed || !control.IsHandleCreated) return;

            control.BeginInvoke(action);
        }
Example #9
0
 static void QueueInvoke(System.Windows.Forms.Control ctl, Action doit)
 {
     if (ctl == null)
     {
         throw new ArgumentNullException("ctl");
     }
     ctl.BeginInvoke(doit);
 }
Example #10
0
 /// <summary>
 /// Simply changes the Width property with smoothing, for any controls
 /// </summary>
 /// <param name="control"></param>
 /// <param name="max">max Width</param>
 /// <param name="distance">Steps in the range (0-1)</param>
 /// <param name="delay">in milliseconds</param>
 public static void effectSmoothChangeWidth(Control control, int max, float distance, int delay)
 {
     distance = Math.Max(0, Math.Min(distance, 1));
     (new System.Threading.Tasks.Task(() =>
     {
         int step = (int)(max * distance);
         while(control.Width < max)
         {
             control.BeginInvoke((MethodInvoker)delegate {
                 control.Width += step;
             });
             System.Threading.Thread.Sleep(delay);
         }
         control.BeginInvoke((MethodInvoker)delegate {
             control.Width = max;
         });
     })).Start();
 }
Example #11
0
		public static void Invoke(this Forms.Control me, Action action)
		{
			if (me.InvokeRequired)
			{
				try { me.BeginInvoke((Delegate)action); }
				catch (System.InvalidOperationException) { }
			}
			else
				action();
		}
Example #12
0
        public static void SafeInvokeAsync(Control ctr, Action action)
        {
            if (ctr == null || ctr.IsDisposed)
                return;

            if (ctr.InvokeRequired)
                ctr.BeginInvoke(action);
            else
                action();
        }
        public static bool BeginInvokeIfControlCanHandleInvoke(Control control, Delegate method)
        {
            if (ControlCanHandleInvoke(control))
            {
                control.BeginInvoke(method);
                return true;
            }

            return false;
        }
Example #14
0
 public static void DoThreadSafe(Control control, MethodInvoker action)
 {
     if (control.InvokeRequired)
     {
         control.BeginInvoke(action);
     }
     else
     {
         action();
     }
 }
Example #15
0
 internal void BeginInvoke(MethodInvoker mi)
 {
     if (ctrlOwner != null)
     {
         ctrlOwner.BeginInvoke(mi);
     }
     else
     {
         mi();
     }
 }
Example #16
0
 /*############# Created By User on Stack OverFlow ###############################*/
 //the function below safely invoke changes that need to happen to the GUI from the backgroundworker thread
 //Or thread they were called on .
 public static void SafeBeginInvoke(System.Windows.Forms.Control control, System.Action action)
 {
     if (control.InvokeRequired)
     {
         control.BeginInvoke(new System.Windows.Forms.MethodInvoker(() => { action(); }));
     }
     else
     {
         action();
     }
 }
Example #17
0
 public static void InvokeOnUiThreadIfRequired(this System.Windows.Forms.Control control, Action action)
 {
     if (control.InvokeRequired)
     {
         control.BeginInvoke(action);
     }
     else
     {
         action.Invoke();
     }
 }
Example #18
0
 public static void AfterAllClear(Control rate, Control pokemonNames)
 {
     if (Settings.Default.NoInputRate) {
         pokemonNames.BeginInvoke((MethodInvoker)(() => {
             pokemonNames.Select();
         }));
     } else {
         rate.BeginInvoke((MethodInvoker)(() => {
             rate.Select();
         }));
     }
 }
 /// <summary>
 /// Attempts to run a delegate method on the UI thread of a System.Windows.Forms.Control
 /// Basically a wrapper around BeginInvoke with testing for readiness / availability of the
 /// control itself
 /// </summary>
 /// <param name="control">Control to run on</param>
 /// <param name="method">delegate method to run</param>
 public static void ExecuteOnUIThread(Control control, Delegate method)
 {
     for (var i = 0; i < 30; i++)
     {
         if (control.IsHandleCreated)
             break;
         if (control.IsDisposed || control.Disposing)
             return;
         Thread.Sleep(100);
     }
     control.BeginInvoke(method);
 }
Example #20
0
 // activate / deactivate control
 public static void ActivateControl(Control aControl, bool aActive)
 {
     if (aControl.InvokeRequired)
     {
         aControl.BeginInvoke(
             new MethodInvoker(delegate() { ActivateControl(aControl, aActive); })
         );
     }
     else
     {
         aControl.Enabled = aActive;
     }
 }
 //***************************************************************************
 // Static Methods
 // 
 /// <summary>
 /// Tells the specified control to invalidate its client area and immediately redraw itself.
 /// </summary>
 /// <param name="ctrl"></param>
 public static void RefreshControl(Control ctrl)
 {
     if (ctrl.InvokeRequired)
     {
         RefreshControlDelegate del = new RefreshControlDelegate(CrossThreadUI.RefreshControl);
         if (CrossThreadUI.ExecSync)
             ctrl.Invoke(del);
         else
             ctrl.BeginInvoke(del);
     }
     else
         ctrl.Invalidate();
 }
Example #22
0
 //http://rsdn.ru/forum/dotnet/2285015.aspx
 /// <summary>
 /// private void SetIntSignalLevel(int SigValue)
 /// {
 /// 	SafeInvoker.Invoke(SigLevel,
 /// 		delegate
 ///			{
 /// 				SigLevel.Value = SigValue;
 /// 		}
 ///		);
 /// }
 /// </summary>
 /// <param name="ctrl"></param>
 /// <param name="methodToInvoke"> delegate { ProgressBar.Value = value; } </param>
 public static void BeginInvoke(Control ctrl, MethodInvoker methodToInvoke)
 {
     try {
         if (ctrl == null || ctrl.IsDisposed)
             return;
         if (ctrl.InvokeRequired) {
             ctrl.BeginInvoke (methodToInvoke);
         } else {
             methodToInvoke ();
         }
     } catch (ObjectDisposedException) {
     }
 }
		/// <summary>
		/// Shows standard decryption error UI within the context of a parent form
		/// </summary>
		public static DecryptionErrorAction OnDecryptionError(Control form, IContentEncryption encryptor)
		{
			if (form.InvokeRequired)
			{
				DecryptionErrorAction result = DecryptionErrorAction.Skip;
				IAsyncResult async = form.BeginInvoke(new MethodInvoker(delegate
				{
					result = ShowDecryptionErrorDialog(form, encryptor);
				}));
				form.EndInvoke(async);
				return result;
			}
			return ShowDecryptionErrorDialog(form, encryptor);
		}
 public static void SetVisible(Control control, bool visible)
 {
     if (control.InvokeRequired)
     {
         control.BeginInvoke(new Action(() =>
         {
             control.Visible = visible;
         }));
     }
     else
     {
         control.Visible = visible;
     }
 }
Example #25
0
        /// <summary>
        /// Invoke and action safely even if called from the background thread.
        /// </summary>
        /// <remarks>
        /// Invoking on the ui thread from background threads works *most* of the time, with occasional crash.
        /// Stackoverflow has a good collection of people trying to deal with these corner cases, where
        /// InvokeRequired(), for example, is unreliable (it doesn't tell you if the control hasn't even
        /// got a handle yet).
        /// SIL.Core (lipalaso) has a SafeInvoke on its LogBox control, which sees heavy background/foreground interaction
        /// and seems to work well over the course of years.
        /// I think I (JH) wrote that, but it relies on a couple of odd things:
        /// 1) it calls IsHandleCreated() (which can reportedly create the handle on the wrong thread?)
        /// and 2) uses SynchronizationContext which works for that single control case but I'm not seeing how
        /// to generalize that.
        /// So now I'm trying something more mainstream here, from a highly voted SO answer.
        /// </remarks>
        public static void Invoke(string nameForErrorReporting, Control control, bool forceSynchronous, bool throwIfAnythingGoesWrong, Action action)
        {
            Guard.AgainstNull(control, nameForErrorReporting); // throw this one regardless of the throwIfAnythingGoesWrong

            //mostly following http://stackoverflow.com/a/809186/723299
            try
            {
                if (control.IsDisposed)
                {
                    throw new ObjectDisposedException("Control is already disposed. (" + nameForErrorReporting + ")");
                }
                if (control.InvokeRequired)
                {
                    var delgate = (Action)delegate { Invoke(nameForErrorReporting, control, forceSynchronous, throwIfAnythingGoesWrong, action); };
                    if (forceSynchronous)
                    {
                        control.Invoke(delgate);
                    }
                    else
                    {
                        control.BeginInvoke(delgate);
                    }
                }
                else
                {
                    // InvokeRequired will return false if the control isn't set up yet
                    if (!control.IsHandleCreated)
                    {
                        //This situation happened in BL-2918, prompting the introduction of this safeinvoke
                        throw new ApplicationException("SafeInvoke.Invoke apparently called before control created ("+ nameForErrorReporting+")");

                        //note, resist the temptation to work around this by just making the handle be created with something like
                        //var unused = control.Handle
                        //I've read a rumour that this can create the handle "on the wrong thread".
                        //At a minimum, we would need to investigate the truth of that before using it here.
                    }
                    action();
                }
            }
            catch (Exception error)
            {
                if (throwIfAnythingGoesWrong)
                    throw;
                else
                {
                    Debug.Fail("This error would be swallowed in release version: " + error.Message);
                    SIL.Reporting.Logger.WriteEvent("**** "+error.Message);
                }
            }
        }
Example #26
0
        private void ProgressDispatcherProc()
        {
            m_stopThreads = false;

            while (!m_stopThreads)
            {
                while (m_progressQueue.Count > 0)
                {
                    ProgressChangedEventArgs args = m_progressQueue.Dequeue();

                    if (ProgressChanged != null)
                    {
                        m_guiMarshaller.BeginInvoke(new MethodInvoker(delegate()
                        {
                            ProgressChanged(this, args);
                        }));
                        Application.DoEvents();
                    }
                }
                // sleep longer if no pregress events are ever coming in
                // keep the thread though in case they turn progress on at some point
                Thread.Sleep(this.WorkerReportsProgress ? 5 : 1000);
            }
        }
		/// <summary>
		/// Shows standard content encryption UI
		/// </summary>
		public static DecryptResult GetPassword(Control form, string attachmentName, string passwordName, string passwordDescription, out string password)
		{
			if (form.InvokeRequired)
			{
				DecryptResult result = DecryptResult.Ok;
				string pwd = string.Empty;
				IAsyncResult async = form.BeginInvoke(new MethodInvoker(delegate
				{
					result = ShowPasswordRequestDialog(form, attachmentName, passwordName, passwordDescription, out pwd);
				}));
				form.EndInvoke(async);
				password = pwd;
				return result;
			}
			return ShowPasswordRequestDialog(form, attachmentName, passwordName, passwordDescription, out password);
		}
Example #28
0
        public static void SimulateMotion(SWF.MenuItem item)
        {
            SWF.Menu    parentMenu;
            SWF.Control wnd = GetWnd(item, out parentMenu);
            if (wnd == null)
            {
                return;
            }

            if (wnd.InvokeRequired)
            {
                wnd.BeginInvoke(new MenuItemOperator(SimulateMotion),
                                item);
                return;
            }

            SWF.MouseEventArgs args = GetMouseArgs(item);
            parentMenu.tracker.OnMotion(args);
        }
Example #29
0
        private unsafe void SetFocusAsync(Message *ptrMessage, int messageNumber)
        {
            //must be first message
            if (messageNumber != 1)
            {
                throw new Exception("SetFocusAsync must be the first message");
            }

            // p1  = handle
            IntPtr control = GetParameterIntPtr(ptrMessage, 0);

            //TODO WPF etc
            WF.Control childControl = WF.Control.FromHandle(control);
            if (childControl != null)
            {
                object[] theParameters = { control };
                childControl.BeginInvoke(m_SetFocusAsyncDelegater, theParameters);
            }
            CleanUpMessage(ptrMessage);
        }
Example #30
0
        public static void BeginInvoke(Control control, MethodInvoker method)
        {
            if (control == null)
              {
            throw new ArgumentNullException("control");
              }

              if (method == null)
              {
            throw new ArgumentNullException("method");
              }

              if (control.InvokeRequired)
              {
            control.BeginInvoke(method, null);
              }
              else
              {
            method();
              }
        }
        /// <summary>
        /// Shows standard content encryption UI
        /// </summary>
        public static DecryptResult GetPasswords(Control form, string attachmentName, string attachmentDisplayName, out string openPassword, out string modifyPassword)
        {
            if (form.InvokeRequired)
            {
                DecryptResult result = DecryptResult.Ok;
                string pwdOpen = string.Empty;
                string pwdModify = string.Empty;

                IAsyncResult async = form.BeginInvoke(new MethodInvoker(delegate
                {
                    result = ShowExtendedPasswordRequestDialog(form, attachmentName, attachmentDisplayName, out pwdOpen, out pwdModify);
                }));
                form.EndInvoke(async);

                openPassword = pwdOpen;
                modifyPassword = pwdModify;

                return result;
            }

            return ShowExtendedPasswordRequestDialog(form, attachmentName, attachmentDisplayName, out openPassword, out modifyPassword);
        }
Example #32
0
 protected override void Invalidate(Control containerControl)
 {
     if (this.DesignMode)
     {
         if (containerControl.InvokeRequired)
             containerControl.BeginInvoke(new MethodInvoker(delegate { containerControl.Invalidate(); }));
         else
             containerControl.Invalidate();
     }
     else
     {
         if (containerControl.InvokeRequired)
             containerControl.BeginInvoke(new MethodInvoker(delegate { containerControl.Invalidate(m_Rect, true); }));
         else
             containerControl.Invalidate(m_Rect, true);
     }
 }
Example #33
0
 // 安全版本
 public static void FilterValueList(Control owner, Control control)
 {
     if (owner.InvokeRequired == true)
     {
         Delegate_filterValue d = new Delegate_filterValue(__FilterValueList);
         owner.BeginInvoke(d, new object[] { control });
     }
     else
     {
         __FilterValueList((Control)control);
     }
 }
Example #34
0
 protected virtual void Update(Control containerControl)
 {
     if (containerControl.InvokeRequired)
         containerControl.BeginInvoke(new MethodInvoker(delegate { containerControl.Update(); }));
     else
         containerControl.Update();
 }
Example #35
0
 protected virtual void Invalidate(Control containerControl)
 {
     if (this.DesignMode)
     {
         if (containerControl is Form && !(containerControl is RadialMenuPopup))
         {
             if (IsHandleValid(containerControl))
                 InvalidateFormCaption(containerControl);
             containerControl.Refresh();
         }
         else
         {
             if (containerControl.InvokeRequired)
                 containerControl.BeginInvoke(new MethodInvoker(delegate { containerControl.Invalidate(); }));
             else
                 containerControl.Invalidate();
         }
     }
     else
     {
         if (containerControl is Form && !(containerControl is RadialMenuPopup))
         {
             if (IsHandleValid(containerControl))
                 InvalidateFormCaption(containerControl);
         }
         else
         {
             if (containerControl.InvokeRequired)
                 containerControl.BeginInvoke(new MethodInvoker(delegate { containerControl.Invalidate(GetInvalidateBounds(), true); }));
             else
                 containerControl.Invalidate(GetInvalidateBounds(), true);
         }
     }
 }
Example #36
0
        private unsafe void PeakMessage(Message *ptrMessage, int messageNumber)
        {
            //must be first message
            if (messageNumber != 1)
            {
                throw new Exception("PeakMessage must be the first message");
            }

            // p1  = handle
            IntPtr handle    = GetParameterIntPtr(ptrMessage, 0);
            int    timeoutMS = GetParameterInt32(ptrMessage, 1);

            int threadId = NM.GetWindowThreadProcessId(handle, out int pid);

            m_AllControls = new List <IntPtr>();
            NM.EnumThreadWindows((uint)threadId, EnumThreadProcedue, IntPtr.Zero);

            Stopwatch timer = Stopwatch.StartNew();

            for (int loop = 0; loop < 2; loop++)
            {
                foreach (IntPtr hWnd in m_AllControls)
                {
                    WF.Control control = WF.Control.FromHandle(hWnd);

                    if (control == null)
                    {
                        //Todo
                    }
                    else
                    {
                        while (true)
                        {
                            bool messageAvailble = false;
                            if (control.IsDisposed)
                            {
                                // Nothing
                            }
                            else if (control.Disposing)
                            {
                                messageAvailble = true; // Don't invoke anything just continue to loop till the control is fully disposed
                            }
                            else if (!control.IsHandleCreated)
                            {
                                // Nothing as to get to here the handle must have existed at some point so it must have been destroyed
                            }
                            else if (control.RecreatingHandle)
                            {
                                messageAvailble = true; // Don't invoke anything just continue to loop till the control has recreated the handle
                            }
                            else if (!control.Enabled)
                            {
                                // Nothing move on to the next window
                            }
                            else
                            {
                                try
                                {
                                    //control.BeginInvoke(m_RefreshControlDelegater, new object[] { control });
                                    IAsyncResult result = control.BeginInvoke(m_PeakMessagDelegater, null);
                                    while (true)
                                    {
                                        int innerLoop = 0;
                                        if (result.IsCompleted)
                                        {
                                            messageAvailble = (bool)control.EndInvoke(result);
                                            break;
                                        }

                                        if (control.IsDisposed)
                                        {
                                            // Nothing
                                            break;
                                        }
                                        else if (control.Disposing)
                                        {
                                            // Don't do anything just continue to loop till the control is fully disposed
                                        }
                                        else if (!control.IsHandleCreated)
                                        {
                                            // Nothing as to get to here the handle must have existed at some point so it must have been destroyed
                                            break;
                                        }
                                        else if (control.RecreatingHandle)
                                        {
                                            messageAvailble = true; // Don't invoke anything just continue to loop till the control has recreated the handle
                                            break;
                                        }
                                        else if (!control.Enabled)
                                        {
                                            // Nothing move on to the next window
                                            break;
                                        }

                                        if (timer.ElapsedMilliseconds > timeoutMS)
                                        {
                                            throw new Exception("Thread failed to have zero messages within timeout");
                                        }

                                        innerLoop++;

                                        if (innerLoop == 100)
                                        {
                                            innerLoop = 0;
                                            Thread.Sleep(15);
                                        }
                                        else
                                        {
                                            Thread.Yield();
                                        }
                                    }
                                }
                                catch (ObjectDisposedException) { }
                                catch (InvalidAsynchronousStateException) { }
                                catch (NullReferenceException) { }
                                catch (InvalidOperationException) { }
                            }

                            if (!messageAvailble)
                            {
                                break;
                            }

                            if (timer.ElapsedMilliseconds > timeoutMS)
                            {
                                throw new Exception("Thread failed to have zero messages within timeout");
                            }

                            Thread.Sleep(15);
                        }
                        break;
                    }
                }
            }

            CleanUpMessage(ptrMessage);
        }
Example #37
0
 void RepairState(Control control, AnimateMode mode)
 {
     control.BeginInvoke(new MethodInvoker(() =>
     {
         switch (mode)
         {
             case AnimateMode.Hide: control.Visible = false; break;
             case AnimateMode.Show: control.Visible = true; break;
         }
     }));
 }
Example #38
0
 public static IAsyncResult BeginInvoke(Control c, Delegate f, params object[] p)
 {
     try
     {
         if (!IsExiting(c))
         {
             return c.BeginInvoke(f, p);
         }
     }
     catch (ObjectDisposedException)
     {
         if (!IsExiting(c)) throw;
     }
     catch (InvalidAsynchronousStateException)
     {
         if (!IsExiting(c)) throw;
     }
     catch (InvalidOperationException)
     {
         if (!IsExiting(c)) throw;
     }
     return null;
 }
 public override void Post(SendOrPostCallback d, object state)
 {
     invoke_control.BeginInvoke(d, new object[] { state });
 }
Example #40
0
        // 安全版本
        /// <summary>
        /// 过滤控件中的列表值
        /// </summary>
        /// <param name="owner">控件的宿主控件</param>
        /// <param name="control">控件</param>
        public static void FilterValueList(Control owner, Control control)
        {

            Delegate_filterValue d = new Delegate_filterValue(__FilterValueList);

            if (owner.Created == false)
                __FilterValueList((Control)control);
            else
                owner.BeginInvoke(d, new object[] { control });

        }
 public static void SetbackgroundImage(Control control, Image image)
 {
     if (control.InvokeRequired)
     {
         control.BeginInvoke(new Action(() =>
         {
             control.BackgroundImage = image;
         }));
     }
     else
     {
         control.BackgroundImage = image;
     }
 }
Example #42
0
 public static void BeginInvoke(Control c, MethodInvoker f)
 {
     try
     {
         if (!IsExiting(c))
         {
             c.BeginInvoke(f);
         }
     }
     catch (ObjectDisposedException)
     {
         if (!IsExiting(c)) throw;
     }
     catch (InvalidAsynchronousStateException)
     {
         if (!IsExiting(c)) throw;
     }
     catch (InvalidOperationException)
     {
         if (!IsExiting(c)) throw;
     }
 }