Move a PictureBox with mouse

后端 未结 6 709
情话喂你
情话喂你 2021-01-03 14:15

I\'m developing an app for windows mobile (Compact Framework 2.0). It has a WinForms with a PictureBox.

I want to move the image of the PictureBox but I don\'t know

6条回答
  •  离开以前
    2021-01-03 15:17

    Actual Code (Requires .NET Framework 3.5 and beyond, not sure if this is available in the Compact Framework)...

    // Global Variables
    private int _xPos;
    private int _yPos;
    private bool _dragging;
    
    // Register mouse events
    pictureBox.MouseUp += (sender, args) =>
    {
        var c = sender as PictureBox;
        if (null == c) return;
        _dragging = false;
    };
    
    pictureBox.MouseDown += (sender, args) =>
    {
        if (args.Button != MouseButtons.Left) return;
        _dragging = true;
        _xPos = args.X;
        _yPos = args.Y;
    };
    
    pictureBox.MouseMove += (sender, args) =>
    {
        var c = sender as PictureBox;
        if (!_dragging || null == c) return;
        c.Top = args.Y + c.Top - _yPos;
        c.Left = args.X + c.Left - _xPos;
    };
    

提交回复
热议问题