【发布时间】:2012-02-24 22:26:38
【问题描述】:
我正在开发自己的个性化 winapi 包装器。我想要的语法是这样的:
// #define wndproc(name) void name (Window & hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
// #define buttonproc(name) void name (Button & hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
wndproc (rightClick) { //evaluates to function to handle window message
::msg ("You right clicked the window. Closing window...");
hwnd.close(); //close() is implemented in my Window class
}
buttonproc (buttonClick) { //same thing basically
::msg ("You clicked this button. I'm going to hide the other one...");
//if text on this button is "One button", find the one belonging to parent
//with the text "Other button" and hide it, or vice-versa
hwnd.text == "One button"
? hwnd.parent().button ("Other button").hide();
: hwnd.parent().button ("One button").hide();
}
int main() {
Window win; //create default window
win.addmsg (WM_LBUTTONDOWN, rightClick); //look for l-click message and call that
Button b1 (win, "One button", 100, 100, 50, 20, buttonClick); //parent, coords, size, clicked
Button b2 (win, "Other button", 200, 100, 50, 20, buttonClick);
return messageLoop(); //should be self-explanatory
}
问题是,在 wndproc 中,hwnd 是 Window &,在 buttonproc 中,hwnd 是 Button &。我也许可以说:
msgproc (Window, rightClick){...}
msgproc (Button, buttonClick){...}
问题在于我必须调用这些程序并赋予它们正确的hwnd。我的主窗口过程在我的Window 类中实现。它得到四个普通参数。如果我需要将WM_COMMAND 消息传递给右键过程,我想给它相应的Button 对象。
按照目前的方式,我将一个指针传递给Window 和Button 的超类。当然,它会创建复杂的代码,例如:
((Window *)hwnd)->operator()() //get HWND of the Window
无论如何,它似乎并没有那么好用。不幸的是,目前我能想到的唯一方法是保留每个创建的Button 的列表,然后取出正确的一个。我什至可以将此扩展到所有可能的收件人。
这样做的好处是我的Button 类有一个静态窗口过程,只要找到WM_COMMAND 消息就会调用它。我没有添加其他控件,但它旨在通过使用现有控件检查 id 并调用您在创建按钮时指定的过程(如果它是匹配的)来工作。问题是,完成后,添加WM_COMMAND 处理程序的任何其他东西(如复选框)也将被调用。
我正在考虑在Window 中保留每个 HWND 子对象及其对应对象的列表。这样我就可以像Button那样对每个类中的额外过程进行核对,这将导致发生大量额外处理,并将proc [i] ((BaseWindow *)hwnd, msg, wParam, lParam)替换为proc [i] (control [loword(wParam)], msg, wParam, lParam)之类的WM_COMMAND,使用lParam看看是不是控件。
我似乎错过了一些重要的东西。我很有可能会开始实现它,然后遇到一个主要问题。有没有更好的方法来完成这一切?
当我这样做时,有没有一种方法可以创建一个 control() 函数来返回正确的对象类型(按钮、复选框...),这取决于它找到对应的 id 而不是一个不同对象的数组(我很确定我已经看到了一种方法)?
【问题讨论】:
-
你显然在使用 C++,那为什么首先要使用宏呢?
-
@Cody Gray,其背后的原因是为了消除常用的参数列表。每次打出来都挺费劲的。
-
好吧,我明白了。为什么不使用虚函数?无论如何,您已经定义了
Window和Button类。 -
你能解释一下我如何使用一个吗?我没有接受提示。
-
如果你不知道虚函数是什么,你需要先得到a book that teaches you the C++ language,然后再继续。一旦你学会了 C++,就从 Raymond Chen 的C++ scratch program 开始,并进行相应的定制。
标签: c++ windows winapi inheritance wrapper