William_von_Baskerville William_von_Baskerville - 3 years ago 168
C# Question

draw from another Methode doesn't work

In this code im creating a Grid in the

Form1
class and by key values, from the arrow keys, I can move a symbol "@" over the Grid, and it works just fine.

If I'm calling the
ComputerPlayer
class the x and y coordinates change like expected (recording to visual studio debugger), but the graphics don't change.

What am I missing?

public class Form1 : Form
{

public Form1()
{
Text = "Form1";
Size = new Size(400, 400);
Paint += new PaintEventHandler(Print);
CenterToScreen();
}

public void Print(object sender, PaintEventArgs e)
{
Graphics graphics = e.Graphics;
int i = 0, j;
DoubleBuffered = true;
Paint += new PaintEventHandler(Cursor);

...
}

public void Cursor(object sender, PaintEventArgs e)
{
Font arialBold = new Font("Arial", 14.0F);
{
TextRenderer.DrawText(e.Graphics, ("@"), arialBold,
new Point(x, y), Color.Red);
}
}
}


public class ComputerPlayer : Form1
{

public void InitiateComputerCursor()
{
if (count-- != 0)
{
Paint += new PaintEventHandler(ComputerCursor);
this.Invalidate();
}
}

private void ComputerCursor(object sender, PaintEventArgs e)
{
DoubleBuffered = true;
Font arialBold = new Font("Arial", 14.0F);
TextRenderer.DrawText(e.Graphics, ("@"), arialBold,
new Point(x, y), Color.Red);
}
}

Answer Source

May be I got it totally wrong but looking at your code it seems you are inheriting from Form1, this is creating two different instances of Form1 but only is shown in the screen so changes to ComputerPlayer will not have any visual effect.

May be you could change the code as follows:

public class ComputerPlayer
{
    private Form1 _form1;

    public ComputerPlayer(Form1 form) 
    {
         _form1 = form;
    }

    public void InitiateComputerCursor()
    {        
        if (count-- != 0)
        {
            _form.Paint += new PaintEventHandler(ComputerCursor);
            _form.Invalidate();
        }
    }

    private void ComputerCursor(object sender, PaintEventArgs e)
    {
        DoubleBuffered = true;
        Font arialBold = new Font("Arial", 14.0F);
         //You might need to replace the following line for a method in form1 that have access to TextRenderer
        _form1.TextRenderer.DrawText(e.Graphics, ("@"), arialBold,
        new Point(x, y), Color.Red);
    }
}

Then whatever you initialize ComputerPlayer in Form1 pass the reference to the constructor:

ComputerPlayer computerPlayer = new ComputerPlayer(this);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download