|
||
|
|
#1 (permalink) |
|
Forum Expert
|
I'll be explaining how to create and use callbacks.
First, I'll start by explaining what a callback is. A callback is basically a pointer to a function that executes when a certain event happens. This could be a button click, a window resize, or anything else. For this example, I'll be creating a button class that has an OnCreate callback. The first thing to do is create the button, here is what I have: Button.h Code:
#pragma once
class Button
{
public:
//
// Fields
//
int X;
int Y;
int Width;
int Height;
//
// Functions
//
Button(int x, int y, int w, int h);
};
Code:
#include "Button.h"
Button::Button(int x, int y, int w, int h)
{
X = x;
Y = y;
Width = w;
Height = h;
}
Main.cpp Code:
#include <stdlib.h>
#include <stdio.h>
#include "Button.h"
int main(int argc, char* argv[])
{
Button* button1 = new Button(5, 5, 100, 26);
printf("button1 created\n");
// So we can see the output. This isn't needed in Visual
// Studio when you start without debugging.
system("PAUSE");
return 0;
}
Button.h Code:
#pragma once
class Button
{
public:
//
// Fields
//
int X;
int Y;
int Width;
int Height;
// Our callback
void (*OnCreateCallback)(void);
//
// Functions
//
Button(int x, int y, int w, int h, void (*callback)(void));
void OnCreate();
};
Code:
#include "Button.h"
Button::Button(int x, int y, int w, int h, void (*callback)(void))
{
X = x;
Y = y;
Width = w;
Height = h;
OnCreateCallback = callback;
// Trigger the callback
OnCreate();
}
void Button::OnCreate()
{
// Make sure the callback isn't null
if(OnCreateCallback != 0)
{
OnCreateCallback();
}
}
Code:
#include <stdlib.h>
#include <stdio.h>
#include "Button.h"
Button* button1;
void Button1Created()
{
printf("button1 created\n");
}
int main(int argc, char* argv[])
{
// When we call the constructor, we're passing the
// name of the function that handles the OnCreate
// event. If you pass 0, the event won't get called
button1 = new Button(5, 5, 100, 26, Button1Created);
// So we can see the output. This isn't needed in Visual
// Studio when you start without debugging.
system("PAUSE");
return 0;
}
Attached is the Visual Studio project.
__________________
Age of Conan Hacks + more to come Visit www . injectsoft . com Last edited by Kitchen_; 07-21-2008 at 11:26 AM. |
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|