C#怎么做一个永远没有焦点的窗口 类似输入法控制栏

[删除(380066935@qq.com或微信通知)]

更好的阅读体验请查看原文:https://blog.csdn.net/accomp/article/details/7209052

在窗体加入如下代码,防止窗体获得焦点

  1. private const int WM_MOUSEACTIVATE = 0x21;
  2. private const int MA_NOACTIVATE = 3;
  3. protected override void WndProc(ref Message m)
  4. {
  5. if (m.Msg == WM_MOUSEACTIVATE)
  6. {
  7. m.Result = new IntPtr(MA_NOACTIVATE);
  8. return;
  9. }
  10. base.WndProc(ref m);
  11. }
  12. protected override bool ShowWithoutActivation
  13. {
  14. get
  15. {
  16. return false;
  17. }
  18. }

 

然后再加入如下代码,防止窗体的控件获得焦点

  1. void SetChildControlNoFocus(Control ctrl)
  2. {
  3. if (ctrl.HasChildren)
  4. foreach (Button c in ctrl.Controls)
  5. {
  6. SetControlNoFocus(c);
  7. }
  8. }
  9. MethodInfo SetControlStyleMethod;
  10. object[] SetControlStyleArgs = new object[] { ControlStyles.Selectable, false };
  11. private void SetControlNoFocus(Button ctrl)
  12. {
  13. SetControlStyleMethod.Invoke(ctrl, SetControlStyleArgs);
  14. SetChildControlNoFocus(ctrl);
  15. }


最后就是在窗体的构造函数部分调用如下代码,完成初始化参数的任务

  1. SetControlStyleMethod = typeof(Button).GetMethod("SetStyle",
  2. BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod);
  3. SetChildControlNoFocus(this);
  4. this.DoubleBuffered = true;
  5. SetStyle(ControlStyles.Selectable, false);
  6. this.TopMost = true;
  7. this.FormBorderStyle = FormBorderStyle.None;
  8. this.ShowIcon = false;
  9. this.ShowInTaskbar = false;


最后这个窗体,就永远无法获得焦点了