winforms 如何使滚动跟随鼠标位置时,pictureBox是缩放面板窗口窗体c#

wr98u20j  于 2022-12-23  发布在  C#
关注(0)|答案(1)|浏览(161)

我有一个pictureBox在一个面板,我一直有问题,编程面板的滚动跟随鼠标在pictureBox中的位置。我把图片框设置在panel的中间,但是如果picturebox1.Width〉panel1.Width,我就把图片框设置在location(0,0),下面是我的代码:

public float scaleModification = 1f;

        private void PictureBox1_MouseWheel(object sender, MouseEventArgs e)
        {
            if (ModifierKeys.HasFlag(Keys.Control))
            {
                setPictureToLocationZero();
                if (e.Delta > 0)
                {
                    scaleModification *= 1.1f;
                    pictureBox1.Scale(new SizeF(1.1f, 1.1f));
                }
                else
                {
                    scaleModification *= 0.9f;
                    pictureBox1.Scale(new SizeF(0.9f, 0.9f));
                }
                setPanelScroll(new PointF(e.X, e.Y));
            }
        }
private void setPanelScroll(PointF mousePos)
        {
            //panel1.ScrollControlIntoView(pictureBox1);
            var p = panel1.AutoScrollPosition;
            p.X = -p.X;
            p.Y = -p.Y;
            p.X += (int)((mousePos.X * scaleModification) - mousePos.X) ;
            p.Y += (int)((mousePos.Y * scaleModification) - mousePos.Y);
            panel1.AutoScrollPosition = new Point(p.X,p.Y);
        }
private void pictureBox1_SizeChanged(object sender, EventArgs e)
        {
            if (pictureBox1.Width > panel1.Width)
            {
                setPictureToLocationZero();
            }
            else
            {
                setPictureToMiddle();
            }
        }
private void setPictureToLocationZero()
        {
            pictureBox1.Location = new Point(0, 0);
        }

        private void setPictureToMiddle()
        {
            int x = (panel1.Width - pictureBox1.Width) / 2;
            int y = (panel1.Height - pictureBox1.Height) / 2;
            pictureBox1.Location = new Point(x,y);
        }

我希望当鼠标滚轮滚动缩放是激活面板的滚动跟随光标在图片框的位置。我将感谢很多任何帮助!

zf2sa74q

zf2sa74q1#

您的代码没有触发鼠标滚轮事件。您需要触发滚轮事件来调整其大小,以达到所需的效果。
触发鼠标滚轮事件的代码如下所示:

public Form1()
    {
        InitializeComponent();
        this.MouseWheel += new MouseEventHandler(Form1_MouseWheel);
    }
[DllImport("user32.dll")]
public static extern int WindowFromPoint(int xPoint, int yPoint);
 
void Form1_MouseWheel(object sender, MouseEventArgs e)
{
    System.Drawing.Point p = PointToScreen(e.Location);
    if (WindowFromPoint(p.X, p.Y) == pictureBox1.Handle.ToInt32())
    {
        if (e.Delta == 120)
        {
            MessageBox.Show("Bigger");
        }
        else if (e.Delta < 0)
        {
            MessageBox.Show("Smaller");
        }
    }
}

相关问题