C#将picturebox保存在form1中

时间:2014-09-01 21:39:17

标签: c#

我在Windows窗体应用程序中有一个可以使用箭头键移动的图片框。我希望它对可以去的地方有一定的限制,特别是在表格中。我该怎么做呢?移动目标的班级如下:

命名空间AmazingPaintball {     类目标     {
        私人点p;

    public Target(Point myPoi)
    {          
        p = myPoi;      
    }

    public Point Move(Keys key)
    {            
            if (key == Keys.Left)
            {
                p.Offset(-50, 0);
            }
            else if (key == Keys.Right)
            {
                p.Offset(50, 0);
            }
            else if (key == Keys.Up)
            {
                p.Offset(0, -50);
            }
            else if (key == Keys.Down)
            {
                p.Offset(0, 50);
            } 
        return p;

    }
}

}

以下是form1:

命名空间AmazingPaintball {

public partial class Form1 : Form
{
    Random positionX = new Random();
    Random positionY = new Random();
    Target einstein;
    int count = 0;
    Paintballs pBalls = new Paintballs();
    Stopwatch stopwatch = new Stopwatch();


    SoundPlayer wavPlayer = new SoundPlayer(@"G:\ChefBrohansPaintballFunNew\ChefBrohansPaintballFun\Resources\singlegunshot.wav");
    SoundPlayer wavPlayer2 = new SoundPlayer(@"G:\ChefBrohansPaintballFunNew\ChefBrohansPaintballFun\bin\Debug\Resources\Applause.wav");


    public Form1()
    {
        InitializeComponent();
        Point point = new Point(positionX.Next(0, 638), positionY.Next(0, 404));
        einstein = new Target(point);
        ptrEinstein.Location = point;    

    }


    private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
        pBalls.paint(e.Graphics);

    }

    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {            
        ptrEinstein.Location = einstein.Move(e.KeyData);                        
        pictureBox1.Update();
        pictureBox1.Refresh();          

    }




    private void pictureBox1_MouseClick(object sender, MouseEventArgs e)
    {
        wavPlayer.Play();
        pBalls.add(e.Location);
        pictureBox1.Refresh();                        
        count++;
    }        

    private void Form1_Load(object sender, EventArgs e)
    {                      
        stopwatch.Start();           

    }

    private void ptrEinstein_MouseClick(object sender, MouseEventArgs e)
    {
        count++;            
        ptrEinstein.Image = Properties.Resources.AlbertEinsteinTongue;
        stopwatch.Stop();            
        wavPlayer2.Play();
        MessageBox.Show("It took " + count + " shots and " + stopwatch.Elapsed + " seconds to hit the target");
        wavPlayer2.Stop();            
        ptrEinstein.Image = Properties.Resources.AlbertEinsteinFace;            
        count = 0;            
        stopwatch.Reset();
        stopwatch.Start();   

    }   


}

}

图片框是ptrEinstein,它能够在form1_keydown事件中移动。

1 个答案:

答案 0 :(得分:0)

当您移动图片框时,请首先检查以确保您将其移动到表单内部。例如。检查新X +图片框的宽度是否小于表格的宽度等。