简体   繁体   English

Visual C ++中的事件处理

[英]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 我将不胜感激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. 编辑:问题是,当我尝试将发件人投射到picurebox时,它给出一个错误,指出无法转换类型。

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#) 动态类型转换将为您提供正确的对象类型(如果可以转换),否则将为null(这与C#中的“ as”等效)

If this does give you a null reference, then perhaps your sender is not what you think it is? 如果确实为您提供了一个空引用,那么您的发件人可能不是您想的那样?

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. 我的Visual C ++有点生锈,现在无法提供代码。

kgiannakakis,问题是当我尝试将发件人转换为picurebox时,出现错误,提示无法转换类型。

您确定发送者对象实际上是您假定的类型吗?

If you're trying the code that Toji gave, then there's you're problem - try this: 如果您尝试使用Toji提供的代码,那么您就有问题了-尝试以下操作:

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 ). 与C#不同,在C#中,不需要任何语法来表示托管堆对象,C ++ \\ CLI区分堆栈对象( PictureBox pb ),指向堆对象的指针( PictureBox *pb )和指向托管堆对象的句柄( PictureBox ^pb )。 。 The three are not the same thing, and have different lifetimes and usages. 这三个不是同一件事,并且具有不同的生存期和用法。

How are you trying to cast? 您如何尝试投射? I'd generally use dynamic_cast or safe_cast : 我通常会使用dynamic_castsafe_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... 从那里应该很简单...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM