Jump to content

  • Log In with Google      Sign In   
  • Create Account

Custom GUI - Assigning functions to buttons


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
15 replies to this topic

#1 Askr   Members   -  Reputation: 117

Like
0Likes
Like

Posted 27 November 2012 - 02:25 AM

Hey there,

so I've been trying to come up with a GUI (using SFML2.0 and C#) and while it's not really a problem to draw stuff onto the screen (or even checking if the mouse is above a button or if the button is clicked), I can't come up with an idea of how to make the buttons functional.

I want to have a class called "Button" with a Property "ButtonFunction". So when I create a button I can also associate an action to be triggered, when I click the button.

Can anyone give me a kickstart here? I'd also appreciate any other information regarding creating a useful custom GUI.
Thanks in advance!

Sponsor:

#2 NightCreature83   Crossbones+   -  Reputation: 3032

Like
0Likes
Like

Posted 27 November 2012 - 03:16 AM

Use a delegate that should be set on the buttonFunction property or passed as a construction parameter to the button class. This way you can provide completely new actions but use the same button class for all of your buttons.
Worked on titles: CMR:DiRT2, DiRT 3, DiRT: Showdown, GRID 2, Mad Max

#3 Askr   Members   -  Reputation: 117

Like
0Likes
Like

Posted 27 November 2012 - 05:19 AM

Thanks for your fast reply. Although I don't quite understand how I can achieve the wanted functionality using delegates. :|
Would you mind elaborating your solution some more?

#4 NightCreature83   Crossbones+   -  Reputation: 3032

Like
2Likes
Like

Posted 27 November 2012 - 06:31 AM

Yeah basically you do this
delegate void ButtonDelegate(); //This can return a value and take parameters and is only the definition of how the function should look

class Button
{
public Button(ButtonDelegate delegate)
{
	 m_delegate = delegate;
}

public onButtonClick()
{
	 m_delegate();
}

private ButtonDelegate m_delegate;
}

static class Wrapper
{
public static void printHelloWorld()
{
	 Console.WriteLn("Hello World! From delegate call"):
}
}

Button button = new Button(Wrapper.printHelloWorld);
button.onButtonClick();
}


See http://msdn.microsoft.com/en-us/library/900fyy8e%28v=vs.80%29.aspx for more information on delegates. A delegate is effictivly a function pointer and it is a way for you to give a function to something else and call that particular function from that something else, this is how callbacks in C/C++ are usually implemented.

Edited by NightCreature83, 27 November 2012 - 06:34 AM.

Worked on titles: CMR:DiRT2, DiRT 3, DiRT: Showdown, GRID 2, Mad Max

#5 Khaiy   Crossbones+   -  Reputation: 1342

Like
0Likes
Like

Posted 27 November 2012 - 08:54 PM

To build on what NightCreature said, you might try looking into C# events. They may not be necessary for what you're intending, but I didn't quite understand delegates until I started working with events. Here are two links that give a decent intro to events in practice.

I've put together a GUI using SFML 2.0 and C#, so if you'd like more information on what I did (which is functional, if inelegant) let me know.

#6 Nypyren   Crossbones+   -  Reputation: 4797

Like
2Likes
Like

Posted 27 November 2012 - 09:53 PM

Parameterless events:

public event Action Click; // add this as a member of the button class

protected virtual void OnClick() // Add this function as a member of the button class
{
    if (Click != null)
        Click(); // This causes all of the attached delegates to be called.
}


// elsewhere, you hook the event using any of the following forms:

// Lambda expression form
button.Click += () => Trace.WriteLine("button clicked!");

// Lambda statement form
button.Click += () =>
{
   // Inline code here
};

// Anonymous method form
button.Click += delegate
{
   // Inline code here
};


// Standard form
button.Click += FunctionName; // Note:  Visual studio will auto-complete this for you if you press TAB twice after typing the +=

and:

void FunctionName()
{
    // Stuff here.
}

Events with parameters:

public event Action<MouseButton> Click; // add this as a member of the button class

protected virtual void OnClick(MouseButton mb) // Add this function as a member of the button class
{
    if (Click != null)
        Click(mb); // This causes all of the attached delegates to be called.
}


// elsewhere, you hook the event using any of the following forms:

// Lambda expression form
button.Click += (mb) => Trace.WriteLine("button clicked: " + mb);

// Lambda statement form
button.Click += (mb) =>
{
   // Inline code here
   Trace.WriteLine("A button was clicked.");
   Trace.WriteLine("It was: "+mb);
};

// Anonymous method form when you don't need the parameter list
button.Click += delegate
{
   // Inline code here
};


// Standard form
button.Click += FunctionName; // Note:  Visual studio will auto-complete this for you if you press TAB twice after typing the +=

and:

void FunctionName(MouseButton mb)
{
    // Stuff here.
}



Edited by Nypyren, 27 November 2012 - 09:59 PM.


#7 3Ddreamer   Crossbones+   -  Reputation: 3169

Like
0Likes
Like

Posted 27 November 2012 - 11:30 PM

I'd also appreciate any other information regarding creating a useful custom GUI.


Sure. Search for Gtk#, a C# application for making GUIs.

MonoDevelop
http://monodevelop.com/
Mono
http://www.mono-project.com/Main_Page

Gtk# - Can be used to make GUIs in C# targeting Mono and/ or .Net Framework.
http://www.mono-project.com/GtkSharp



Clinton

Personal life and your private thoughts always effect your career. Research is the intellectual backbone of game development and the first order. Version Control is crucial for full management of applications and software.  The better the workflow pipeline, then the greater the potential output for a quality game.  Completing projects is the last but finest order.

 

by Clinton, 3Ddreamer


#8 Askr   Members   -  Reputation: 117

Like
0Likes
Like

Posted 28 November 2012 - 01:34 AM

Wow, thanks guys! That's certainly some interesting stuff to work through.

@NightCreature83
Thanks for explaining, I think I got it now! If I understood correctly delegates might be exactly what I've been looking for.

@Khaiy

I've put together a GUI using SFML 2.0 and C#, so if you'd like more information on what I did (which is functional, if inelegant) let me know.

Sure thing, hit me up with anything you got. I'd love to see how you did it. Posted Image

@Nypyren

// Standard form
button.Click += FunctionName;

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?

@3Ddreamer
Thanks for those links, but I was referring to GUIs in games. Although Gtk# looks promising I don't think I could find a use for it within my current project. Posted Image

#9 3Ddreamer   Crossbones+   -  Reputation: 3169

Like
0Likes
Like

Posted 28 November 2012 - 01:44 AM

Gtk# is being used in games as well as other programs.


Clinton

Personal life and your private thoughts always effect your career. Research is the intellectual backbone of game development and the first order. Version Control is crucial for full management of applications and software.  The better the workflow pipeline, then the greater the potential output for a quality game.  Completing projects is the last but finest order.

 

by Clinton, 3Ddreamer


#10 Askr   Members   -  Reputation: 117

Like
0Likes
Like

Posted 28 November 2012 - 03:46 AM

Gtk# is being used in games as well as other programs.

Is that so? I figured from a quick overview that it was not. Then I shall look into it some more. :)

#11 Nypyren   Crossbones+   -  Reputation: 4797

Like
1Likes
Like

Posted 28 November 2012 - 11:52 AM

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[i] = new Button();
    buttons[i].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.

Edited by Nypyren, 28 November 2012 - 11:55 AM.


#12 Askr   Members   -  Reputation: 117

Like
0Likes
Like

Posted 14 December 2012 - 03:10 AM

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?

#13 BCullis   Crossbones+   -  Reputation: 1813

Like
0Likes
Like

Posted 14 December 2012 - 08:27 AM

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.

Edited by BCullis, 14 December 2012 - 08:27 AM.

Hazard Pay :: FPS/RTS in SharpDX
DeviantArt :: Because right-brain needs love too

#14 Khaiy   Crossbones+   -  Reputation: 1342

Like
0Likes
Like

Posted 14 December 2012 - 08:34 PM

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().

Edited by Khaiy, 14 December 2012 - 10:20 PM.


#15 Askr   Members   -  Reputation: 117

Like
0Likes
Like

Posted 18 December 2012 - 01:13 AM

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? :)

Edited by Askr, 18 December 2012 - 01:14 AM.


#16 Khaiy   Crossbones+   -  Reputation: 1342

Like
0Likes
Like

Posted 18 December 2012 - 02:52 AM

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.

Edited by Khaiy, 18 December 2012 - 03:05 AM.





Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS