ThreadControlHelper.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using System.Windows.Forms;
  8. namespace Common
  9. {
  10. /// <summary>
  11. /// 控件委托帮助类
  12. /// </summary>
  13. public class ThreadControlHelper
  14. {
  15. /// <summary>
  16. /// 跨线程设置控件属性值委托类型定义
  17. /// </summary>
  18. delegate void SetControlPropertyCallBack(Control control, string name, object value);
  19. /// <summary>
  20. /// 跨线程设置控件属性值
  21. /// </summary>
  22. public static void SetControlProperty(Control control, string name, object value)
  23. {
  24. if (control.InvokeRequired == true)
  25. {
  26. SetControlPropertyCallBack CallBack = new SetControlPropertyCallBack(SetControlProperty);
  27. control.Invoke(CallBack, new object[] { control, name, value });
  28. }
  29. else
  30. {
  31. Type type = control.GetType();
  32. type.InvokeMember(name,
  33. BindingFlags.Public | BindingFlags.SetProperty | BindingFlags.Instance,
  34. null, control, new object[] { value });
  35. }
  36. }
  37. /// <summary>
  38. /// 跨线程设置控件属性值委托类型定义
  39. /// </summary>
  40. delegate object GetControlPropertyCallBack(Control control, string name);
  41. /// <summary>
  42. /// 跨线程读取控件属性值
  43. /// </summary>
  44. public static object GetControlProperty(Control control, string name)
  45. {
  46. if (control.InvokeRequired == true)
  47. {
  48. GetControlPropertyCallBack CallBack = new GetControlPropertyCallBack(GetControlProperty);
  49. return control.Invoke(CallBack, new object[] { control, name });
  50. }
  51. else
  52. {
  53. Type type = control.GetType();
  54. return type.InvokeMember(name,
  55. BindingFlags.Public | BindingFlags.GetProperty | BindingFlags.Instance,
  56. null, control, null);
  57. }
  58. }
  59. }
  60. }