public bool ContainsText() { var containsText = false; GuiThreadControl?.Invoke((MethodInvoker)(() => { containsText = Clipboard.ContainsText(); })); return(containsText); }
/// <summary> /// 登録された情報でクライアントを作成して返します。エラー発生時は null を返します。 /// </summary> /// <param name="showError">エラー発生時にメッセージボックスを出力するか。</param> /// <param name="control">プログレスバーの存在するコントロール。</param> /// <param name="progressBar">進捗状況を表示するプログレスバー。</param> /// <returns>作成したクライアント。エラー発生時は null を返します。</returns> public async Task <MastodonClient> CreateClient(bool showError, Control control = null, ProgressBar progressBar = null) { // Mastodon Instance へのアプリケーションの登録 AuthenticationClient authClient; AppRegistration appRegistration; try { authClient = new AuthenticationClient(instance); appRegistration = await authClient.CreateApp(Assembly.GetExecutingAssembly().GetName().Name, Scope.Read | Scope.Write | Scope.Follow); } catch (Exception e) { logger.ErrorFormat($"{instance}: サーバ接続に失敗 - {e.Message}"); if (showError) { Utilities.ShowError($"{instance} に接続できません。\nドメイン名を確認してください。"); } return(null); } control?.Invoke((MethodInvoker)(() => progressBar.Value = 33)); // アクセストークンの取得 Auth auth; try { auth = await authClient.ConnectWithPassword(email, password); } catch (Exception e) { logger.ErrorFormat($"{instance}: アカウントへの接続に失敗 - {e.Message}"); if (showError) { Utilities.ShowError("アカウントに接続できません。\nメールアドレス・パスワードを確認してください。"); } return(null); } control?.Invoke((MethodInvoker)(() => progressBar.Value = 66)); // クライアントを作成 client = new MastodonClient(appRegistration, auth); var user = await client.GetCurrentUser(); AccountName = $"{user.UserName}@{instance}"; Icon = user.AvatarUrl; control?.Invoke((MethodInvoker)(() => progressBar.Value = 100)); return(client); }
private static void ThreadPoolColorAnimation(object obj) { object[] objs = obj as object[]; Control control = objs[0] as Control; Color color = (Color)objs[1]; int time = (int)objs[2]; Func <Control, Color> getColor = (Func <Control, Color>)objs[3]; Action <Control, Color> setcolor = (Action <Control, Color>)objs[4]; int count = (time + TimeFragment - 1) / TimeFragment; Color color_old = getColor(control); try { for (int i = 0; i < count; i++) { control.Invoke(new Action(() => { setcolor(control, Color.FromArgb( GetValue(color_old.R, color.R, i, count), GetValue(color_old.G, color.G, i, count), GetValue(color_old.B, color.B, i, count))); })); Thread.Sleep(TimeFragment); } control?.Invoke(new Action(() => { setcolor(control, color); })); } catch { } }
private static void InvokeActionBefore() { if (Thread.CurrentThread.ManagedThreadId == _uiThreadId) { InvokeActionBeforeUiThread(); } else { _mainForm?.Invoke((MethodInvoker) delegate { InvokeActionBeforeUiThread(); }); } }
public static void AutoInvoke(this Control ctrl, Action worker) { if (ctrl.InvokeRequired) { _ = ctrl?.Invoke((MethodInvoker) delegate { worker?.Invoke(); }); } else { worker?.Invoke(); } }
public static void RunInUiThreadIgnoreErrorThen(Control control, Action uiUpdater, Action next) { if (control == null || control.IsDisposed) { return; } void done() { _ = Task.Run(() => { try { next?.Invoke(); } catch { } }); } void TryUpdateUi() { try { uiUpdater?.Invoke(); } catch { } } if (!control.InvokeRequired) { TryUpdateUi(); done(); return; } try { control?.Invoke((MethodInvoker) delegate { TryUpdateUi(); done(); }); return; } catch { } done(); }
/// <summary> /// 在控件上同步调用 /// </summary> /// <typeparam name="TReturn">返回类型</typeparam> /// <typeparam name="TDelegate">委托签名</typeparam> /// <param name="control"></param> /// <param name="delegate"></param> /// <param name="params"></param> /// <returns></returns> /// <remarks>传参时,频繁传入值类型,会因为与 object 的装箱拆箱而导致性能问题</remarks> public static TReturn InvokeIfRequired <TReturn, TDelegate>(this Control control, TDelegate @delegate, params object[] @params) where TDelegate : Delegate { if (@delegate == null || @delegate.Method == null) { throw new ArgumentNullException(nameof(@delegate)); } var tReturn = typeof(TReturn); var dReturn = @delegate.Method.ReturnType; if (dReturn != tReturn && !dReturn.IsSubclassOf(tReturn)) { throw new ArgumentException($"{nameof(TReturn)}泛型返回值类型 {tReturn.Name} 与委托返回值类型 {dReturn.Name} 不匹配"); } var args = @delegate.Method.GetParameters(); int maxLength = args.Length; int minLength = args.Count(p => !p.IsOptional); if (@params.Length < minLength || @params.Length > maxLength) { throw new ArgumentException($"传入的实际参数数量({args.Length}) 与 委托的形式参数数量({minLength}~{maxLength}) 不匹配"); } try { if (control == null || !control.InvokeRequired) { return((TReturn)@delegate.DynamicInvoke(@params)); } else { return((TReturn)control?.Invoke(new Func <object>(() => @delegate.DynamicInvoke(@params)))); } } catch (Exception ex) { LogHelper <Delegate> .ErrorException(ex, "执行 Invoke 委托失败:"); throw; } }
public static Bitmap Snapshot(Control c, int width = 0, int height = 0) { IntPtr hwnd = IntPtr.Zero; IntPtr dc = IntPtr.Zero; c.Invoke(new MethodInvoker(() => { if (width == 0) { width = c.ClientSize.Width; } if (height == 0) { height = c.ClientSize.Height; } hwnd = c.Handle; dc = GetDC(hwnd); })); Bitmap bmp = new Bitmap(width, height, PixelFormat.Format32bppRgb); if (dc != IntPtr.Zero) { try { using (Graphics g = Graphics.FromImage(bmp)) { IntPtr bdc = g.GetHdc(); try { BitBlt(bdc, 0, 0, width, height, dc, 0, 0, TernaryRasterOperations.SRCCOPY); } finally { g.ReleaseHdc(bdc); } } } finally { ReleaseDC(hwnd, dc); } } return bmp; }
/// <summary> /// 在控件上同步调用 /// </summary> /// <param name="control"></param> /// <param name="delegate"></param> /// <param name="params"></param> /// <returns></returns> /// <remarks>传参时,频繁传入值类型,会因为与 object 的装箱拆箱而导致性能问题</remarks> public static object InvokeIfRequired(this Control control, Delegate @delegate, params object[] @params) { try { if (control == null || !control.InvokeRequired) { return(@delegate.DynamicInvoke(@params)); } else { return(control?.Invoke(new Func <object>(() => @delegate.DynamicInvoke(@params)))); } } catch (Exception ex) { LogHelper <Delegate> .ErrorException(ex, "执行 Invoke 委托失败:"); throw; } }
void RepairState(Control control, AnimateMode mode) { invokerControl.Invoke(new MethodInvoker(() => { try { switch (mode) { case AnimateMode.Hide: control.Visible = false; break; case AnimateMode.Show: control.Visible = true; break; } } catch { //form was closed } })); }
public void doMessage(flag myflag, object message, string success) { try { if (delegMessage != null) { Control target = delegMessage.Target as Control; if (target != null && target.InvokeRequired) { target.Invoke(delegMessage, new object[] { this, message, myflag, success }); } else { delegMessage(this, message, myflag, success); } } } catch (Exception e) { //Log. } }
public static void ShowInfo(IWin32Window owner, string text, float timeCloseSecond = 3.5f) { try { Control ctrl = owner as Control; if (ctrl == null) { Form main = Application.OpenForms[0]; foreach (var item in Application.OpenForms) { FrmMain form = item as FrmMain; if (form != null) { main = form; break; } } ctrl = main; } ctrl.Invoke(new Action(() => { FrmInfo frmInfo = new FrmInfo(text, timeCloseSecond); if (ctrl == null) { frmInfo.Show(); } else { frmInfo.Show(ctrl); } frmInfo.Refresh(); })); } catch (Exception ex) { } }
public static void SetPropertyValue(Control ctrl, string propertyName, object value, params object[] args) { if (ctrl.InvokeRequired) { SetPropertyDelegate del = new SetPropertyDelegate(CrossThreadUI.SetPropertyValue); if (CrossThreadUI.ExecSync) { ctrl.Invoke(del, ctrl, propertyName, value, args); } else { ctrl.BeginInvoke(del, ctrl, propertyName, value, args); } } else { Type ctrlType = ctrl.GetType(); PropertyInfo pi = ctrlType.GetProperty(propertyName, Binding); // Make sure the object "Value" matches the property's Type. if (!value.GetType().IsAssignableFrom(pi.PropertyType)) { throw new ArgumentException("Value Type does not match property Type.", "value"); } if (pi != null) { try { pi.SetValue(ctrl, ((pi.PropertyType.FullName == "System.String") ? value.ToString() : value), args); } catch { throw; } } else { throw new ArgumentException("Specified control does not expose a '" + propertyName + "' property.", "propertyName"); } } }
private static void SwitchControlState(Control container, string identity, ControlState _controlState = ControlState.Lock) { try { if ((container.GetType() == typeof(TabControl) || container.GetType().Namespace.Contains("XtraTabControl"))) { if (container.InvokeRequired) { container.Invoke(new Action(delegate() { SwitchControlState(container.Parent, identity, _controlState); })); } else { SwitchControlState(container.Parent, identity, _controlState); } return; } foreach (var control in container.Controls) { if (((Control)control).Name == identity) { continue; } if (((Control)control).InvokeRequired) { ((Control)control).Invoke(new MethodInvoker(() => { ((Control)control).Enabled = _controlState != ControlState.Lock; })); continue; } ((Control)control).Enabled = _controlState != ControlState.Lock; } } catch { } }
public void SetControlText(Control con, string text, bool changeSize) { try { if (string.IsNullOrEmpty(text)) { return; } if (con.InvokeRequired) { MyDelagete md = new MyDelagete(SetControlText); con.Invoke(md, con, text, changeSize); } else { if (changeSize) { if (text.Length > 9) { con.Font = new Font(con.Font.Name, con.Font.Size - 2, con.Font.Style); } if (text.Length > 12) { con.Font = new Font(con.Font.Name, con.Font.Size - 1, con.Font.Style); } if (text.Length > 18) { con.Font = new Font(con.Font.Name, con.Font.Size - 1, con.Font.Style); } } con.Text = text; } } catch { } }
public void CloseLogfile() { if (!m_LogLoaded) { return; } m_LogFile = ""; m_Renderer.CloseThreadSync(); m_Renderer = new RenderManager(); m_APIProperties = null; m_FrameInfo = null; m_DrawCalls = null; m_Buffers = null; m_Textures = null; m_D3D11PipelineState = null; m_GLPipelineState = null; m_PipelineState.SetStates(null, null, null); m_LogLoaded = false; foreach (var logviewer in m_LogViewers) { Control c = (Control)logviewer; if (c.InvokeRequired) { c.Invoke(new Action(() => logviewer.OnLogfileClosed())); } else { logviewer.OnLogfileClosed(); } } }
public static void DoThreadSafe(this Control objControl, Action funcToRun) { if (objControl == null || funcToRun == null) { return; } try { Control myControlCopy = objControl; //to have the Object for sure, regardless of other threads if (myControlCopy.InvokeRequired) { myControlCopy.Invoke(funcToRun); } else { funcToRun.Invoke(); } } catch (ObjectDisposedException) // e) { //we really don't need to care about that. //Log.Trace(e); } catch (InvalidAsynchronousStateException e) { //we really don't need to care about that. Log.Trace(e); } catch (Exception e) { Log.Error(e); #if DEBUG Program.MainForm.ShowMessageBox(e.ToString()); #endif } }
/// <summary> /// 执行UI动作 /// </summary> /// <param name="sender">发送者</param> /// <param name="actionName">动作名称</param> /// <param name="actionParameters">动作参数</param> /// <param name="asyncRun">异步执行</param> public void DoUIAction(object sender , string actionName , IEnumerable <object> actionParameters , bool asyncRun = false) { if (UIActing != null) { var eventArgs = new UIActionEventArgs() { ActionName = actionName, ActionParameters = actionParameters }; if (asyncRun) { Task.Factory.StartNew(() => { Container.Invoke(UIActing, sender, eventArgs); }); } else { UIActing(sender, eventArgs); } } }
/// <summary> /// 循环调用某个无返回值的方法 /// </summary> /// <param name="time">毫秒</param> /// <param name="timeout">超时时间</param> /// <param name="con">基于某个控件的方法</param> /// <param name="e">执行事件</param> public static void TimersMethod(int time, int timeout, Control con, ElapsedEventHandler e) { try { // 延迟1毫秒执行方法 System.Timers.Timer timer = new System.Timers.Timer(time); int tt = 0; ElapsedEventHandler handler = (object sender, ElapsedEventArgs e1) => { if (timeout != -1 && tt >= timeout) { timer.Dispose(); } if (con != null) { if (con.InvokeRequired) { con.Invoke(new EventHandler(delegate(object obj, EventArgs e2){ e.Invoke(sender, e1); })); } } else { e.Invoke(sender, e1); } tt += time; }; // 到达时间的时候执行事件; timer.Elapsed += handler; // 设置是执行一次(false)还是一直执行(true); timer.AutoReset = true; // 是否执行System.Timers.Timer.Elapsed事件; timer.Enabled = true; } catch (Exception ex) { Console.WriteLine(ex); } }
public TimedEventsManager(Control control, params TimedEvent[] timedEvents) { _control = control; Action current = null; // Create a method chain, beginning by the last and attaching it // the previous. for (var i = timedEvents.Length - 1; i >= 0; i--) { var i1 = i; var next = current; current = () => { Thread.Sleep(timedEvents[i1].Interval); // MUST run it on the UI thread! _control.Invoke(new Action(() => timedEvents[i1].Action())); if (next != null) { next(); } }; } _chain = current; }
public static object SafelyOperate(Control context, Delegate method, params object[] args) { if (context == null) { throw new ArgumentNullException("context"); } if (method == null) { throw new ArgumentNullException("method"); } if (!(context.IsHandleCreated)) { return(null); } if (context.InvokeRequired) { return(context.Invoke(method, args)); } else { return(method.DynamicInvoke(args)); } }
public static object SafelyOperated(Control context, Delegate process, params object[] args) { if (context == null) { throw new ArgumentNullException("context"); } if (process == null) { throw new ArgumentNullException("process"); } if (!(context.IsHandleCreated)) { return(null); } if (context.InvokeRequired) { return(context.Invoke(process, args)); } else { return(process.DynamicInvoke(args)); } }
public static void SetPropertyThreadSafe <TResult>( this Control @this, Expression <Func <TResult> > property, TResult value) { if (!(property.Body is MemberExpression)) { return; } var propertyInfo = ((MemberExpression)property.Body).Member as PropertyInfo; if (propertyInfo == null || [email protected]().IsSubclassOf(propertyInfo.ReflectedType ?? throw new InvalidOperationException()) || @this.GetType().GetProperty( propertyInfo.Name, propertyInfo.PropertyType) == null) { throw new ArgumentException("The lambda expression 'property' must reference a valid property on this Control."); } if (@this.InvokeRequired) { @this.Invoke(new SetPropertyThreadSafeDelegate <TResult> (SetPropertyThreadSafe), @this, property, value); } else { @this.GetType().InvokeMember( propertyInfo.Name, BindingFlags.SetProperty, null, @this, new object[] { value }); } }
private async Task <ScriptState <object> > ExecuteOnUIThread(Script <object> script, ScriptState <object> stateOpt) { return(await((Task <ScriptState <object> >)s_control.Invoke( (Func <Task <ScriptState <object> > >)(() => { try { return (stateOpt == null) ? script.RunAsync(_globals, CancellationToken.None) : script.ContinueAsync(stateOpt, CancellationToken.None); } catch (FileLoadException e) when(e.InnerException is InteractiveAssemblyLoaderException) { Console.Error.WriteLine(e.InnerException.Message); return Task.FromResult <ScriptState <object> >(null); } catch (Exception e) { // TODO (tomat): format exception Console.Error.WriteLine(e); return Task.FromResult <ScriptState <object> >(null); } }))).ConfigureAwait(false)); }
private async Task <ScriptState <object> > ExecuteOnUIThread(Script <object> script, ScriptState <object> stateOpt) { return(await((Task <ScriptState <object> >)s_control.Invoke( (Func <Task <ScriptState <object> > >)(async() => { try { var task = (stateOpt == null) ? script.RunAsync(_globals, CancellationToken.None) : script.RunFromAsync(stateOpt, CancellationToken.None); return await task.ConfigureAwait(false); } catch (FileLoadException e) when(e.InnerException is InteractiveAssemblyLoaderException) { Console.Error.WriteLine(e.InnerException.Message); return null; } catch (Exception e) { Console.Error.Write(_replServiceProvider.ObjectFormatter.FormatException(e)); return null; } }))).ConfigureAwait(false)); }
private void _ListDevice(object needCheckDriver) { if (OnListDeviceChangeComplete != null) { if ((bool)needCheckDriver) { driverHelper.EmunAndInstallDriver(); } lock (this) { Thread.Sleep(1000); AndoridDevice[] devices = adbHelper.ListDevice(); Control target = OnListDeviceChangeComplete.Target as Control; if (target != null) { target.Invoke(OnListDeviceChangeComplete, new object[] { devices }); } else { OnListDeviceChangeComplete(devices); } } } }
/// <summary> /// <para>Perform an <see cref="Action" /> on the control's thread.</para> /// </summary> /// <param name="control"></param> /// <param name="action"> </param> /// <seealso /> public static void InvokeAction(this Control control, Action action) { if (control == null) { throw new ArgumentNullException(nameof(control)); } if (action == null) { throw new ArgumentNullException(nameof(action)); } if (control.InvokeRequired) { if (!control.IsDisposed) { control.Invoke(action); } } else { action(); } }
private void SetControlPropertyValue(Control oControl, string propName, object propValue) { // http://www.shabdar.org/cross-thread-operation-not-valid.html if (oControl.InvokeRequired) { SetControlValueCallback d = new SetControlValueCallback(SetControlPropertyValue); oControl.Invoke(d, oControl, propName, propValue); } else { Type t = oControl.GetType(); PropertyInfo[] props = t.GetProperties(); foreach (PropertyInfo p in props) { if (p.Name == propName) { p.SetValue(oControl, propValue, null); return; } } throw new ApplicationException(string.Format("Could not find property {0} in object {1}", propName, oControl)); } }
private static T Call <T>( long i_webView, long i_control, long cancelPtr, string jsFunction, FunctionParamterCollection paramterCollection) { IntPtr controlPtr = new IntPtr(i_control); Control control = Control.FromHandle(controlPtr); return((T)control.Invoke(new Func <long, T>(w => { try { IntPtr wV = new IntPtr(w); var es = MBApi.wkeGlobalExec(wV); var args = paramterCollection.ToJsValue(es); var script = string.Format(FUNCTION_CALL_FORMAT, jsFunction); var funV = MBApi.jsEvalW(es, script); if (MBApi.jsIsUndefined(funV)) { return default(T); } long resV = MBApi.jsCallGlobal(es, funV, args, args.Length); var obj = JsConvert.ConvertJSToObject(es, resV, typeof(T)); if (obj == null) { return default(T); } return (T)obj; } catch (Exception ex) { return default(T); } }), i_webView)); }
/// <summary> /// Enable or disable behaviour triggering controls on the user proteinInterface. /// </summary> /// <param name="enabledValue">True to enable. False to disable.</param> public static void SetControlsEnabledProperty(Control control, Control[] controlsToSkip, bool enabledValue) { if (control == null || !control.Created) { return; } if (controlsToSkip == null || !controlsToSkip.Contains(control)) { if (control.InvokeRequired) { control.Invoke(new MethodInvoker(delegate() { //lock (control) { control.Enabled = enabledValue; } })); } else { //lock (control) { control.Enabled = enabledValue; } } } foreach (Control childControl in control.Controls) { //if (!controlsToSkip.Contains(childControl)) { SetControlsEnabledProperty(childControl, controlsToSkip, enabledValue); } } }
/// <summary> /// Method to fire event to subscribers. Subscriber can read the Server.Connected property /// to update a control. /// </summary> /// <param name="b"></param> void OnServerConnected(bool b) { // Make a copy for thread safety EventHandler <ServerCustomEventArgs> copy = ServerConnected; // If event is wired, fire it! if (copy != null) { // Get the target and safe cast it. Control target = copy.Target as Control; // If the target is a control and invoke is required, // invoke it; otherwise just fire it normally. if (target != null && target.InvokeRequired) { object[] args = new object[] { null, new ServerCustomEventArgs(b) }; target.Invoke(copy, args); } else { copy(null, new ServerCustomEventArgs(b)); } } }
/// <summary> /// Sets the text for the specified control in multithreading circumstances. /// </summary> /// <param name="control"></param> /// <param name="text"></param> public static void SetControlVisible(Control control, bool val) { if (control != null) { if (control.InvokeRequired) { SetControlVisibleSafe2 scts = new SetControlVisibleSafe2(SetControlVisible); control.Invoke(scts, new Object[] { control, val }); } else { control.Visible = val; } } }
public void setControlTheme(Control set_me, string to_me) { if(set_me.InvokeRequired) { set_me.Invoke(new setControlThemeDelegate(setControlTheme), new Object[] { set_me, to_me}); } else { lock(set_me) { SetWindowTheme(set_me.Handle,to_me,null); } } }
/// <summary> /// Sets the text for the specified control in multithreading circumstances. /// </summary> /// <param name="control"></param> /// <param name="text"></param> public static void SetControlText(Control control, String text) { if (control != null) { if (control.InvokeRequired) { SetControlTextSafe scts = new SetControlTextSafe(SetControlText); control.Invoke(scts, new Object[] { control, text }); } else { control.Text = text; } } }