문제

Since a week iam learning/working with System.Drawing. It works fine for me. Now i want to transfer data from Form 1 to my second Form and want to have 2 Rectangles drawn on my Form 2 after Form 2 loaded. How do i do that?

What i have tried so far:

  • Invoke on Form 2_Load

  • onPaint() <-- cant transfer Data

  • event show (Form event) ...

(The Code below only works if i press a button on the second Form after Form 2 is loaded.)

Thats how my code looks like for this part:

Form 1:

private void btnGo_Click(object sender, EventArgs e)
    {
        List<string> _basen = new List<string>(); //Add some stuff
        _basen.Add("400;200;45");
        _basen.Add("400;200;45");
        Feld f = new Feld();
        this.Hide();  
        f.transferGameBase(_basen);
        f.ShowDialog();
    }

Form 2:

public void transferGameBase(List<string> infoBase)
    {
        int count = 0;

        foreach(string _base in infoBase)
        {
            string[] _splitter = infoBase[count].ToString().Split(';');
            drawBase(Convert.ToInt16(_splitter[0]), Convert.ToInt16(_splitter[1]), Convert.ToInt16(_splitter[2])); //[0] = x , [1] = y, [2] = size
            count++;
        }
        
    }

    private void drawBase(int x, int y, int size)
    {
            Graphics g = CreateGraphics();
            g.FillRectangle(new SolidBrush(Color.Red), x, y, size, size);
 
    }

Thanks for any answer =)!

도움이 되었습니까?

해결책

try this:

public void transferGameBase(List<string> infoBase)
    {
        int count = 0;

        foreach(string _base in infoBase)
        {
            string[] _splitter = infoBase[count].ToString().Split(';');
            drawBase(Convert.ToInt16(_splitter[0]), Convert.ToInt16(_splitter[1]), Convert.ToInt16(_splitter[2])); //[0] = x , [1] = y, [2] = size
            count++;
        }

        this.Invalidate();

    }

Basically, windows only redraws the form when it actually needs to, so when you manually draw something on top of it, you need to tell the form to redraw itself.

다른 팁

You could force the paint even to use your graphics with the InvokePaint method

 private void drawBase(int x, int y, int size)
    {
            Graphics g = CreateGraphics();
            g.FillRectangle(new SolidBrush(Color.Red), x, y, size, size);
            this.InvokePaint(this, new PaintEventArgs(g, this.Bounds));

    }

But this still won't do anything since the graphics is created before the object is shown, and is prolly not what you want.

You should prolly add the rectangles to a variable on the form and handle drawing those in the Paint event.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top