Event Handling in Visual C ++
There are two images with two different images.
If I click on one block of the image, the image in it should be cleared.
To make matters worse, both picture boxes only have one common event handler. How can I find out which image is generating the event? I would appreciate the 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 send the sender to picurebox it gives an error saying the types cannot be converted.
How do you make the cast? In most cases, I would use:
PictureBox ^pb = safe_cast<PictureBox^>(sender);
if(pb != null) {
// logic goes here
}
(Note that I fixed the above code after Josh pointed out my mistake. Thanks!)
a dynamic cast will give you the type of object you want if it can do, or null if it can't (that's the C # equivalent of "how")
If that gives you a null reference, then maybe your sender is not what you think?
You can use the sender object. Transfer it to the image control unit and compare it with the two available boxes.
My Visual C ++ is a little rusty and can't provide the code now.
kgiannakakis, The problem is when I try to send the sender to picurebox, it gives an error saying that the types cannot be converted.
Are you sure the sender object is actually the type that you assume?
If you are trying to use the code that Toji gave, then you cannot solve this problem:
PictureBox ^pb = safe_cast<PictureBox^>(sender);
Unlike C #, where you don't need the syntax to denote heap managed objects, C ++ \ CLI distinguishes between stack objects ( PictureBox pb
), heap object pointers ( PictureBox *pb
), and handles heap managed objects ( PictureBox ^pb
). These three are not the same thing, and have different lifetimes and uses.
How are you trying to quit? I usually used dynamic_cast
either 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 ...