笔者把STemWin官方给的自定义控件demo进行了精简,得出了这个最简单的自定义控件实现方法,所有代码如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <string.h>
#include "GUI.h"
#include "WM.h"
typedef struct {
  char str[50];
} MYWIDGET_Obj;
static void _cbMyWidget(WM_MESSAGE * pMsg) {
  GUI_RECT WinRect;
  MYWIDGET_Obj MyWidget;
  switch (pMsg->MsgId) {
  case WM_PAINT:
    WM_GetWindowRectEx(pMsg->hWin, &WinRect);
    GUI_MoveRect(&WinRect, -WinRect.x0, -WinRect.y0);
    GUI_SetColor(GUI_YELLOW);
    GUI_Clear();
    WM_GetUserData(pMsg->hWin, &MyWidget, sizeof(MYWIDGET_Obj));
    if(MyWidget.str)
    {
        GUI_DispStringInRect(MyWidget.str, &WinRect, GUI_TA_HCENTER | GUI_TA_VCENTER);
    }
    break;
  }
}
WM_HWIN MYWIDGET_Create(int x0, int y0, int xSize, int ySize, WM_HWIN hWinParent, U32 Style, const char * pText) {
  WM_HWIN   hWin;
  MYWIDGET_Obj      MyWidget;
  if (pText) {
    strcpy(MyWidget.str,  pText);
  }
  hWin = WM_CreateWindowAsChild(x0, y0, xSize, ySize, hWinParent, Style, _cbMyWidget, sizeof(MYWIDGET_Obj));
  WM_SetUserData(hWin, &MyWidget, sizeof(MYWIDGET_Obj));
  return hWin;
}

代码的核心就是WM_CreateWindowAsChild这个函数,你把你的自定义控件的位置、大小、父窗口、回调函数、申请内存大小等传给它,它就在父窗口中创建你的自定义控件了。
MYWIDGET_Obj这个结构体就是你的自定义控件的数据结构,包含它需要用到的全局变量,这个例子我只写了一个字符串在里面。

在WM_CreateWindowAsChild创建控件成功后,你就可以使用WM_SetUserData函数往你的自定义控件里面写东西了,这个例子中,写的就是str这个字符串,最后你的自定义控件的回调函数_cbMyWidget会被调用,在它的重绘命令中你就可以根据需要,使用STemWin的API画出你的自定义控件了。

运行效果如下: