Niyaz
Niyaz

Reputation: 54793

Event handling in Visual C++

There are two pictureboxes with two different images.

If I click on one picture box, the image in it should be cleared.

To make the matters worse, both of the picture boxes have only one common event handler. How can I know which picturebox generated the event? I would appreciate source code in C++-CLI

I need to know what to write inside the function:

private: System::Void sqaure_Click(System::Object^  sender, System::EventArgs^  e) {

}

EDIT: The problem is that when I try to cast sender to picurebox, it gives an error saying that the types cannot be converted.

Upvotes: 0

Views: 3039

Answers (6)

shash
shash

Reputation: 965

How are you trying to cast? I'd generally use dynamic_cast or safe_cast:

PictureBox ^ pb = dynamic_cast<PictureBox^>(sender);
if (pb != nullptr)
{
...
}

or

try
{
    PictureBox ^ pb = safe_cast<PictureBox^>(sender);
    ...
}
catch(InvalidCastException ^ exp)
{
    // Handle a cast that went awry
}

It should be pretty straight-forward from there...

Upvotes: 0

Toji
Toji

Reputation: 34498

How are you doing the cast? In most cases like this I would use:

PictureBox ^pb = safe_cast<PictureBox^>(sender);
if(pb != null) {
    // logic goes here
}

(Note that I've corrected the above code after Josh pointed out my reference flaw. Thanks!)

the dynamic cast will give you the right object type if it can cast, or null if it cant (it's the equiv. of "as" in C#)

If this does give you a null reference, then perhaps your sender is not what you think it is?

Upvotes: 4

Eclipse
Eclipse

Reputation: 45493

If you're trying the code that Toji gave, then there's you're problem - try this:

PictureBox ^pb = safe_cast<PictureBox^>(sender);

Unlike C#, where you don't need any syntax to denote managed heap objects, C++\CLI differentiates between stack objects (PictureBox pb), pointers to heap objects (PictureBox *pb), and handles to managed heap objects (PictureBox ^pb). The three are not the same thing, and have different lifetimes and usages.

Upvotes: 0

Nailer
Nailer

Reputation: 2436

Are you sure the sender object actually is the type you assume it to be?

Upvotes: 0

Niyaz
Niyaz

Reputation: 54793

kgiannakakis, The problem is that when I try to cast sender to picurebox, it gives an error saying that the types cannot be converted.

Upvotes: 0

kgiannakakis
kgiannakakis

Reputation: 104178

You can use the sender object. Cast it to a picture box control and compare it with the two available picture boxes.

My Visual C++ is a little bit rusty and can't provide code now.

Upvotes: 0

Related Questions