Attempt to raise C # event

I studied MANY other answers and examples about this, and I just get more and more confused about how to do this. I need to raise an event in the Robot class based on the result of the executeMove method in the form class. I know that I cannot raise an event from another class, so obviously I am not working. But I really don't understand how to properly configure this. I read articles from delegates and events about codeProject, dreamInCode and this site, among many others. This is for a C # beginner class, and I'm pretty new to this, as I'm sure everyone can say :)

namespace Assignment12
{
    public delegate void ErrorHandler();

public partial class frmRobot : Form
{
    Robot moveRobot = new Robot();

    public frmRobot()
    {
        InitializeComponent();
        reset_Position();
        current_Position_Display();
        moveRobot.outOfRange += new ErrorHandler(moveRobot.coor_Within_Range);
    }
    ...

    private void performMove()
    {
        Point loc = lblArrow.Location;
        int x = moveRobot.Move_Robot_XAxis(loc.X);
        int y = moveRobot.Move_Robot_YAxis(loc.Y);
        if (x < -100 && x > 100)
        {
            moveRobot.outOfRange();
            x = loc.X;
        }
        if (y < -100 && y > 100)
        {
            moveRobot.outOfRange();
            y = loc.Y;
        }
        this.lblArrow.Location = new Point(x, y);
        current_Position_Display();
    }

class Robot
{

    public event ErrorHandler outOfRange;
    ...
    public void coor_Within_Range()
    {
        System.Console.WriteLine("TestOK");

    }
}
+5
source share
3 answers

This question is rather confusing.

, : , . : "" "". , . ? , , ? , , ?

, , - . , , . , . , , : , , . , , , ! , , , .

, , . , , . , , , .

+13

, , . moveRobot.coor_Within_Range(). :

    if (x < -100 && x > 100)
    {
        moveRobot.coor_Within_Range();
        x = loc.X;
    }

In_Range outOfRange .

, , . , .

+2

Your coor_Within_Rangeshould raise an event:

public void coor_Within_Range()
{
    System.Console.WriteLine("TestOK");
    if (this.outOfRange != null) {
        this.outOfRange();
    }
}

Then in your class Formyou need to handle the event:

public frmRobot()
{
    // snipped
    moveRobot.outOfRange += new ErrorHandler(this.oncoor_Within_Range);
}

public void oncoor_Within_Range() {
    Console.WriteLine("robot within range");
}
0
source

All Articles