Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/298.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从另一种形式中抽取_C#_Winforms_Drawing - Fatal编程技术网

C# 从另一种形式中抽取

C# 从另一种形式中抽取,c#,winforms,drawing,C#,Winforms,Drawing,我正在制作一个简单的游戏(c#Win Forms),其中我的角色在关键事件(箭头)上移动 主要类别: switch(e.Keycode) { case Keys.Left: creature.moveleft(this,speed); } 我的生物类如下所示: public void Left(object sender,int speed) { Form form = (Form)sender; Graphics grp = form.CreateGrap

我正在制作一个简单的游戏(c#Win Forms),其中我的角色在关键事件(箭头)上移动

主要类别:

switch(e.Keycode)
{
    case Keys.Left:
    creature.moveleft(this,speed);
}
我的生物类如下所示:

public void Left(object sender,int speed)
{
    Form form = (Form)sender;

     Graphics grp = form.CreateGraphics();
    ..
    ..
    ..
}
我不喜欢每次我想画画的时候都要通过
这个
。最后,对于生物类中的每个绘制方法,我都使用了
formform=(Form)sender

有更好的方法吗

我想,如果我从我的生物类中的
表单
继承,然后使用
Graphics grp=this.CreateGraphics
可以工作,但实际上它不会绘制任何东西


谢谢

如果您的生物类是在表单创建之后创建的,为什么不将表单作为参数传递给构造函数,例如:

public class Creature
{
    private Form form;

    public Creature(Form form)
    {
        this.form = form;
    }

    ...

    public void Left(int speed)
    {
        Graphics grp = form.CreateGraphics();
        ..
        ..
        ..
    }
}

建议:如果您打算在表单上绘制,请使用
Paint
事件在表单中绘制
CreateGraphics
总是一个糟糕的选择。这是正确的,但要回答的问题要大得多!@DonBoitnott@Chris Ballard那么使用绘画活动的正确方式是什么?为什么CreateGraphics是糟糕的选择?谢谢@DonBoitnott你能给我举一个如何使用绘画活动的例子吗?谢谢,上面的代码应该会有帮助,但请记住,当您在前面移动其他窗口时看到奇怪的重画问题时,其他建议etc
CreateGraphics
会生成一个临时绘图表面,它可能在您看到它之前就被擦除了。方法选择不当。使用表单的
Paint
方法绘制表单本身。