C# 如何从其他方法访问控件

C# 如何从其他方法访问控件,c#,class,variables,object,scope,C#,Class,Variables,Object,Scope,我正在制造太空入侵者,我希望我的子弹从我的大炮所在的位置射出。当我按下空格键时,子弹会开火,但我需要它能够在每次按下空格键时访问我的加农炮的位置,它不允许我访问它的信息 public void tsbtnStart_Click(object sender, EventArgs e) { // Make invader Invader invaderX = new Invader(); pnlBattleField

我正在制造太空入侵者,我希望我的子弹从我的大炮所在的位置射出。当我按下空格键时,子弹会开火,但我需要它能够在每次按下空格键时访问我的加农炮的位置,它不允许我访问它的信息

    public void tsbtnStart_Click(object sender, EventArgs e)
    {

        // Make invader

            Invader invaderX = new Invader();
            pnlBattleField.Controls.Add(invaderX);

        // Mke UFO

            Ufo ufoX = new Ufo();
            pnlBattleField.Controls.Add(ufoX);


        // Make cannon
            Cannon cannonX = new Cannon(this.pnlBattleField.Height - 80);

        if (made == false)
        {
            pnlBattleField.Controls.Add(cannonX);
            made = true;

        }
        Point location = cannonX.PointToScreen(Point.Empty);


        tmrClock.Interval = 200;
        tmrClock.Start();
        tmrClock2.Interval = 100;
        tmrClock2.Start();
    }

    public void Form1_KeyPress(object sender, KeyPressEventArgs e)
    {

        if (e.KeyChar == (char)Keys.Space)
        {

            Bullet bulletX = new Bullet(this.pnlBattleField.Height - 80, location.x );
            // "location does not exist in current context

            pnlBattleField.Controls.Add(bulletX);
        }

    }

location
cannonX
tsbtnStart\u Click
中的局部变量,因此一旦
tsbtnStart\u Click
返回,它们就不再存在。将它们设置为类的属性,以便它们能够持久化并在
Form1\u KeyPress
和其他方法中可访问。

好吧,您声明

Point location = cannonX.PointToScreen(Point.Empty);
在您的方法中:

public void tsbtnStart_Click(object sender, EventArgs e)
您需要在开始时在类成员中声明此位置。 之后,您将用正确的值覆盖他的值

像这样:

private Point location = new Point();
location = cannonX.PointToScreen(Point.Empty); // in your method

您需要获取对窗体上的
Cannon
对象的引用,该对象当前位于
pnlBattleField.Controls
中。您需要引用该对象;因此,您可以访问。您还必须传递X轴和Y轴上的坐标值。如何引用对象?嗨,谢谢您的帮助。你能帮我把它们变成我的类的属性吗。我想我必须把它们加入我的加农炮课?我是这样做的:public int location{get{return location;}}我迷路了,请帮助像@Sebastien post一样,你可以添加如下内容:
private Point location到类本身。你可以把它放在你的方法之前或之后。然后,您可以使用两种方法访问相同的
位置。