在winforms中,如何使控件不接受鼠标事件

时间:2014-06-11 19:28:35

标签: c# winforms

我有一个按钮,然后在鼠标中心弹出一个小小的表格,按下鼠标左键后,小形状消失了。我需要这种形式不接受任何鼠标事件,换句话说,是"隐形"对老鼠。

问题是,表单会弹出鼠标,这会触发按钮的mouseleave事件。我知道还有其他方法可以解决这个问题,但是当鼠标离开触发表单的原始按钮时,我需要隐藏表单,我还需要在鼠标下方显示该表单。

那么如何才能使小弹出窗口对鼠标事件不可见,这样它就不会导致鼠标离开"事件触发按钮?

弹出窗口的类型为" Form"。这是触发显示和隐藏表单的mouseEnter和mouseLeave代码:

private void btnPatientSearch_MouseEnter(object sender, EventArgs e)
        {
                _currentPatientInfo = new PatientInfo()
                {
                    MdiParent = this.MdiParent
                };
                _currentPatientInfo.Show();
                _currentPatientInfo.Location = new Point(181, 9);
            }
        }

        private void btnPatientSearch_MouseLeave(object sender, EventArgs e)
        {
            if (_currentPatientInfo == null) return;
            _currentPatientInfo.Hide();
            _currentPatientInfo = null;
        }

1 个答案:

答案 0 :(得分:1)

从以下表单类继承您的弹出窗体。这段代码使用了一些p / invokes而没有经过测试,但它应该有效。

public class PopupForm : Form
{
  private const int WS_BORDER = 0x00800000;
  private const int WS_POPUP = unchecked((int)0x80000000);

  private const int WS_EX_TOPMOST = 0x00000008;
  private const int WS_EX_NOACTIVATE = 0x08000000;

  private const int WM_MOUSEACTIVATE = 0x0021;
  private const int MA_NOACTIVATEANDEAT = 4;

  private static readonly IntPtr HWND_TOPMOST = (IntPtr)(-1);

  private const int SWP_NOSIZE = 0x0001;
  private const int SWP_NOMOVE = 0x0002;
  private const int SWP_NOACTIVATE = 0x0010;

  [DllImport("user32.dll")]
  [return: MarshalAs(UnmanagedType.Bool)]
  private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter,
    int X, int Y, int cx, int cy, int uFlags);

  public PopupForm()
  {
    SetStyle(ControlStyles.Selectable, false);
    FormBorderStyle = FormBorderStyle.None;
    StartPosition = FormStartPosition.Manual;
    ShowInTaskbar = false;
    Visible = false;
  }

  protected override CreateParams CreateParams
  {
    get
    {
      CreateParams cp = base.CreateParams;
      cp.Style |= WS_POPUP | WS_BORDER;
      cp.ExStyle |= WS_EX_TOPMOST | WS_EX_NOACTIVATE;
      return cp;
    }
  }

  protected override bool ShowWithoutActivation
  {
    get { return true; }
  }

  protected override void WndProc(ref Message m)
  {
    if (m.Msg == WM_MOUSEACTIVATE)
    {
      OnClick(EventArgs.Empty);
      m.Result = (IntPtr)MA_NOACTIVATEANDEAT;
    }
    else
      base.WndProc(ref m);
  }

  public new void Show()
  {
    Windows.SetWindowPos(Handle, HWND_TOPMOST, 0, 0, 0, 0,
      SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOMOVE);
    base.Show();
  }
}