天天看點

Combo Box的簡單使用(Win32)

一 Combo Box函數簡單介紹

1 SendMessage函數向視窗發送消息

LRESULT SendMessage(

  HWND hWnd,     // handle to destination window

  UINT Msg,      // message

  WPARAM wParam, // first message parameter

  LPARAM lParam   // second message parameter

);

2 向Combo Box添加資料

HWND hWndComboBox = GetDlgItem(hWnd, IDC_COMBO1);

TCHAR szMessage[20] = "Hello";

SendMessage(hWndComboBox , CB_ADDRSTRING, 0, (LPARAM)szMessage);

3 向Combo Box插入資料

HWND hWndComboBox = GetDlgItem(hWnd, IDC_COMBO1);

TCHAR szMessage[20] = "World";

SendMessage(hWndComboBox , CB_INSERTRSTRING, 0, (LPARAM)szMessage);

4 向Combo Box删除資料

SendMessage(hWndComboBox, CB_DELETESTRING, 1, 0);    //删除第二項資料

5 清除Combo Box所有資料

SendMessage(hWndComboBox, CB_RESETCONTENT, 0, 0);

6 擷取Combo Box資料項目的數量

UINT uCount;

uCount = SendMessage(hWndComboBox, CB_GETCOUNT, 0, 0):

7 擷取Combo Box某項的值

TCHAR szMessage[200];

ZeroMessage(szMessage, sizeof(szMessage)):

SendMessage(hWndComboBox, CB_GETLBTEXT, 1, (LPARAM)szMessage);    //擷取第二項的資料

MessageBox(NULL, szMessage, " ", MB_OK);

二 Combo Box簡單使用

1 界面設計如下圖

Combo Box的簡單使用(Win32)

2 功能實作代碼(建的是簡單的Win32工程)

//ComboBox.cpp
#include "stdafx.h"
#include "resource.h"

LRESULT CALLBACK Dialog(HWND, UINT, WPARAM, LPARAM);

int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                     int       nCmdShow)
{
 	// TODO: Place code here.
	DialogBox(hInstance, (LPCTSTR)IDD_DIALOG1, NULL, (DLGPROC)Dialog);
	return 0;
}

LRESULT CALLBACK Dialog(HWND hWnd, UINT uMessage, WPARAM wParam, LPARAM lParam)
{
	switch(uMessage)
	{
	case WM_INITDIALOG:
		return TRUE;

	case WM_COMMAND:
		UINT uSender;
		uSender = LOWORD(wParam);
		HWND hWndComboBox;
		hWndComboBox = GetDlgItem(hWnd, IDC_COMBO1);
		TCHAR szBuff[200];
		ZeroMemory(szBuff, sizeof(szBuff));
		switch(uSender)
		{
		//CB_ADDSTRING是在最後添加資料
		case IDC_BUTTON1:
			GetDlgItemText(hWnd, IDC_EDIT1, szBuff, sizeof(szBuff));
			SendMessage(hWndComboBox, CB_ADDSTRING, 0, (LPARAM)szBuff);
			break;

		//CB_ADDSTRING是在指定位置添加資料
		case IDC_BUTTON2:
			GetDlgItemText(hWnd, IDC_EDIT1, szBuff, sizeof(szBuff));
			SendMessage(hWndComboBox, CB_INSERTSTRING, 0, (LPARAM)szBuff);
			break;

		case IDC_BUTTON3:
			SendMessage(hWndComboBox, CB_RESETCONTENT, 0, 0);
			break;

		case IDC_BUTTON4:
			UINT uCount;
			uCount = SendMessage(hWndComboBox, CB_GETCOUNT, 0, 0);
			SetDlgItemInt(hWnd, IDC_EDIT2, uCount, TRUE);
			break;
			
		case IDC_BUTTON5:
			UINT uSelect;
			uSelect = GetDlgItemInt(hWnd, IDC_EDIT2, NULL, TRUE);
			SendMessage(hWndComboBox, CB_GETLBTEXT, uSelect, (LPARAM)szBuff);
			MessageBox(hWnd, szBuff, "SHOW", MB_OK|MB_ICONINFORMATION);
			break;

		case IDOK:
			EndDialog(hWnd, lParam);
			break;
		}
		break;

	case WM_CLOSE:
		EndDialog(hWnd, lParam);
		break;
	}
	return FALSE;
}