Custom GUI - Assigning functions to buttons

Started by
14 comments, last by Khaiy 11 years, 4 months ago

I always did stuff like this. The first time I heard of lambda expressions was from your post and although I read the msdn article about lambda expressions by now I'm still a bit lost. You say I could use any of those forms, but do the prior ones do anything better than the standard form?


Yes. The Lambda and anonymous methods are allowed to "capture" or "close over" variables in scope, which isn't available with a standard function.

This is most often used when you're using lambdas in LINQ:


Console.WriteLine("Please enter a search word:");

string word = Console.ReadLine();

List<Record> matches = allRecords.Where(record => record.Keywords.Contains(word)).ToList(); // "word" is being captured by the lambda


In the above example, it's not immediately apparent how powerful capturing variables is. The variables are captured EVEN AFTER they go out of scope of the function that declared them!

This means you can do things like this:


Button[] buttons = new Button[10];

for (int i=0; i<buttons.Length; ++i)
{
int buttonID = i; // NOTE: If you capture a variable incremented by a loop, bad things happen! You must assign a separate variable, otherwise all lambdas will capture a single variable.
buttons = new Button();
buttons.Click += delegate
{
MessageBox.Show("Button " + buttonID + " was clicked!"); // If I use "i" here instead of "buttonID", all buttons would print "Button 10 was clicked!".
};
}


And the button handlers will still work even after the function which contained this code exits.
Advertisement
Sorry for being absent from this topic so long, but I came around testing all your input just now. :]

Everything compiles well enough and I'm almost positive I didn't write anything too stupid, but somehow it just doesn't work. Let me paste some code and tell you what it does (and more importantly, what it does not):

This is from my Program.cs - I spared out the parts I don't consider interesting (FillColor and the like).

Window myWindow = new Window(50, 50, 400, 200);
Button myButton = new Button(0, 0, 150, 25);
myButton.setFillColor(new Color(255, 0, 0));
myButton.Click += new Action(myButton_Click);
myWindow.Add(myButton);

myWindow.Draw();
while (MainWindow.IsOpen())
{
MainWindow.DispatchEvents();
MainWindow.Display();
}

[...]

static void myButton_Click()
{
Console.Write("foo");
}


This is my button class

public event Action Click;
protected virtual void OnClick()
{
if (Click != null)
Click();
}

public Button(int x, int y, int w, int h)
{
this.X = x;
this.Y = y;
this.Width = w;
this.Height = h;
}


When I run the program the window with a button inside of it pops up, but wherever I click, the corresponding method just isn't called. It came to me that I don't have anything defined yet that does any mouse handling, so I figured I have to do this first. Here however I'm at a loss again. :/ Right now I have this Class called "GuiItem" from which "Button" and "Window" inheret. Should I add MouseEventHandlers for keeping track of the mouse in there, or rather create something new?
Try replacing
myButton.Click += new Action(myButton_Click);
with
myButton.Click += myButton_Click;
or
myButton.Click += () => {Console.Write("foo");};

From what I can tell in the MSDN article, the constructor format of Action doesn't do what you're thinking it does. I'll gladly take some correction on that if I didn't search deep enough though.

Hazard Pay :: FPS/RTS in SharpDX (gathering dust, retained for... historical purposes)
DeviantArt :: Because right-brain needs love too (also pretty neglected these days)

Your syntax looks right for subscribing to the event. When are you calling the OnClick() method from the Button class? If that method isn't being called, then the Click event isn't being raised.

I would track the mouse position and whether or not it's been clicked in the Window class, and then if the position of the cursor is inside of myButton when a click is dispatched call myButton.OnClick().

-------R.I.P.-------

Selective Quote

~Too Late - Too Soon~


Try replacing
myButton.Click += new Action(myButton_Click);
with
myButton.Click += myButton_Click;
or
myButton.Click += () => {Console.Write("foo");};

From what I can tell in the MSDN article, the constructor format of Action doesn't do what you're thinking it does. I'll gladly take some correction on that if I didn't search deep enough though.

Sorry, this doesn't work. It doesn't even compile due to syntax errors.


I would track the mouse position and whether or not it's been clicked in the Window class, and then if the position of the cursor is inside of myButton when a click is dispatched call myButton.OnClick().

That was my thought as well. Since you already made a GUI: How did you listen for the mouse? Did you add an own class for this or where did you put it? :)
SFML already has a mouse class, so you probably won't need to make one.

The way that mine is set up is in my abstract Screen class I have a method called OnMouseClick. In the main program, after creating the window but before the game loop I register the OnMouseClick event with the Window.MouseButtonPressed event:



RenderWindow myWindow = new RenderWindow(new VideoMode(800, 600), "My Window");

myWindow.Closed += new EventHandler(OnClose);
myWindow.MouseButtonPressed += new EventHandler<MouseButtonEventArgs>(currentGameScreen.OnMouseClick);



So for every screen that needs to accept mouse input, I have code parsing any input events that are passed to them. The event handler above accepts MouseButtonEventArgs which is descended from EventArgs:



public override void OnMouseClick(object sender, EventArgs e)
{
// Since it comes from a mouse click event, EventArgs argument e carries an enum indicating which mouse input was dispatched with that
// event. So we check what it is:
if (e.Code == SFML.Window.Mouse.Button.Left)
{
// Check if cursor is within the button's clickable region
if (SFML.Mouse.GetPosition(myWindowsName) == // Within myButton's borders)
{
// Execute myButton's left mouse click function
}
}
}



The thing to remember is that the SFML Window class is set up to receive keyboard and mouse input, so the window is where the listening happens. In my game screen's base class I have a public virtual method OnMouseClick, which is empty. That way any descendant can ignore mouse input by default but still pass it along to child elements. If an object gets the mouse button event argument and uses that particular input, it does whatever it's supposed to do.

-------R.I.P.-------

Selective Quote

~Too Late - Too Soon~

This topic is closed to new replies.

Advertisement