gpt4 book ai didi

c# - 鼠标滚轮事件 (C#)

转载 作者:IT王子 更新时间:2023-10-29 04:17:43 26 4
gpt4 key购买 nike

我无法在主窗体中获取鼠标滚轮事件。

作为演示,我想出了一个简单的例子:

public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();

this.panel1.MouseWheel += new MouseEventHandler(panel1_MouseWheel);
this.panel1.MouseMove += new MouseEventHandler(panel1_MouseWheel);

Form2 f2 = new Form2();
f2.Show(this);
}

private void panel1_MouseWheel(object sender, MouseEventArgs e)
{
if(e.Delta != 0)
Console.Out.WriteLine(e.Delta);
}
}

public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();

this.MouseMove += new MouseEventHandler(Form2_MouseMove);
this.MouseWheel += new MouseEventHandler(Form2_MouseMove);
}

private void Form2_MouseMove(object sender, MouseEventArgs e)
{
if(e.Delta != 0)
Console.Out.WriteLine(e.Delta);
}
}

我在 Form2 中获得鼠标滚轮事件但在 Form1 中没有任何想法?

干杯,

詹姆斯

最佳答案

我怀疑 OP 想要在鼠标悬停在面板上时获取滚动事件,即使面板没有焦点。

此处解释了实现此行为的方法:

http://social.msdn.microsoft.com/forums/en-US/winforms/thread/eb922ed2-1036-41ca-bd15-49daed7b637c/

这里:

http://social.msdn.microsoft.com/forums/en-US/winforms/thread/6bfb9287-986d-4c60-bbcc-23486e239384/

取自链接论坛的代码片段之一:

using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace WindowsApplication1 {
public partial class Form1 : Form, IMessageFilter {
public Form1() {
InitializeComponent();
Application.AddMessageFilter(this);
}

public bool PreFilterMessage(ref Message m) {
if (m.Msg == 0x20a) {
// WM_MOUSEWHEEL, find the control at screen position m.LParam
Point pos = new Point(m.LParam.ToInt32() & 0xffff, m.LParam.ToInt32() >> 16);
IntPtr hWnd = WindowFromPoint(pos);
if (hWnd != IntPtr.Zero && hWnd != m.HWnd && Control.FromHandle(hWnd) != null) {
SendMessage(hWnd, m.Msg, m.WParam, m.LParam);
return true;
}
}
return false;
}

// P/Invoke declarations
[DllImport("user32.dll")]
private static extern IntPtr WindowFromPoint(Point pt);
[DllImport("user32.dll")]
private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);
}
}

此代码基本上会拦截所有 wm_mousewheel 事件并将它们重定向到鼠标当前悬停的控件。面板不再需要焦点来接收滚轮事件。

关于c# - 鼠标滚轮事件 (C#),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/479284/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com