我有一个解决方案,里面有两个项目。拿到代码后,他们告诉我其中一个项目处理视觉部分,另一个项目处理逻辑部分。现在我向窗口添加了一个按钮,为此我编辑了处理视觉部分的项目。我很新手,但是在Visual Studio 2010中创建和添加按钮非常简单。现在的问题是,我想检测是否从另一个项目按下了按钮。我确定这些项目正在共享一些数据,但是我无法捕获它。目前,我正在更改文件中的值,并从另一个项目读取相同的数据以检查是否按下了按钮。但我认为有更好的方法可以做到这一点。有人可以帮忙吗?
// Solution A (Controller - logic part)
// MyUIHandler.h
class IMyUIHandler //You can also use microsoft's interface keyword for something similar.
{
public:
HRESULT onButtonPressed() = 0; // Note that you can also add parameters to onButtonPressed.
};
HRESULT getMyUIHandler(IMyUIHandler **ppHandler);
然后实现这个接口:
// Solustion A (Controller - logic part)
// MyUIHandler.cpp
#include "MyUIHandler.h"
class CMyUIHandler : public IMyUIHandler
{
private:
// Add your private parameter here for anything you need
public:
HRESULT onButtonPressed();
}
HRESULT getMyUIHandler(IMyUIHandler **ppHandler)
{
// There are many ways to handle it here:
// 1. Define a singleton object CMyUIHandler in your project A. Just return a pointer
// to that object here. This way the client never releases the memory for this
// object.
// 2. Create an instance of this object and have the client release it. The client
// would be responsible for releasing the memory when it's done with the object.
// 3. Create an instance of this object and have a class/method in Solution A release
// the memory.
// 4. Reference count the object, for example, make IUnknown the parent class of
// IMyUIHandler, and implement the IUnknown interace (which is boiler plate code).
// Since I don't know your project it's hard for me to pick the most suitable one.
...
*ppHandler = myNewHandler;
...
return S_OK;
}
CMyUIHandler可以简单地成为您已经处理某些逻辑的现有类。
在方案B中,您应该在一些初始化函数(例如UI类的控制器)中调用getMyUIHandler,将其保存为成员。然后是由VS为您创建的“Button clicked”事件处理程序。
// Solution B (View - visual part)
// MyUIView.h
class MyUIView
{
protected:
IMyUIHandler *m_pHandler;
}
// MyUIView.cpp
CMyUIView::CMyUIView(...)
{
...
hr = getMyUIHandler(&m_pHandler);
// error handler, etc...
...
}
// In the function that is created for you when button is clicked (I'm not sure if I get the signature right below.
void OnClick(EventArgs^ e)
{
...
hr = m_pHandler->onButtonPressed();
...
}
当按钮被点击时,您可以传递任何您为函数onButtonPressed定义的参数。