From 8e957dc0546a3b127f6970f5c459868c2bd868a7 Mon Sep 17 00:00:00 2001 From: "Valeriano A.R" Date: Mon, 20 Jul 2020 20:50:27 +0200 Subject: [PATCH] ControlsUtils.SetControlPropertyThreadSafeDelegate: Method to change properties of controls in a thread safe way. --- VAR.Toolbox/Controls/ControlsUtils.cs | 30 ++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/VAR.Toolbox/Controls/ControlsUtils.cs b/VAR.Toolbox/Controls/ControlsUtils.cs index 64a0935..3ece0f2 100644 --- a/VAR.Toolbox/Controls/ControlsUtils.cs +++ b/VAR.Toolbox/Controls/ControlsUtils.cs @@ -1,4 +1,5 @@ -using System.Windows.Forms; +using System.Reflection; +using System.Windows.Forms; namespace VAR.Toolbox.Controls { @@ -8,5 +9,32 @@ namespace VAR.Toolbox.Controls { return size * 96f / ctrl.CreateGraphics().DpiX; } + + private delegate void SetControlPropertyThreadSafeDelegate( + Control control, + string propertyName, + object propertyValue); + + public static void SetControlPropertyThreadSafe( + Control control, + string propertyName, + object propertyValue) + { + if (control.InvokeRequired) + { + control.Invoke(new SetControlPropertyThreadSafeDelegate + (SetControlPropertyThreadSafe), + new object[] { control, propertyName, propertyValue }); + } + else + { + control.GetType().InvokeMember( + propertyName, + BindingFlags.SetProperty, + null, + control, + new object[] { propertyValue }); + } + } } }