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.
source to share
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?
source to share
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.
source to share
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 ...
source to share