在C++ Builder中使用系統內建的IP地址編輯框。
1、BCB工程中,在需要使用IP地址框的表單裡面。
首先引用標頭檔,再申明變數。
#include "SysIPAddress.hpp"TSysIPAddress32 *ipaddr;
2、在FormCreate事件中建立該控制項,並指定位置:
ipaddr = new TSysIPAddress32(this); ipaddr->Parent = this; ipaddr->Left = 5; ipaddr->Top = 5;
3、使用控制項:
int nIP; AnsiString ss; ipaddr->Enabled = false; if (ipaddr->IsEmpty) ShowMessage("IP地址為空白?"); //擷取IP地址 Edit1->Text = ipaddr->Text; nIP = ipaddr->IPAddr; ss.sprintf( " | 0x%X", nIP ); Edit1->Text = Edit1->Text + ss; ipaddr->ClearIP(); nIP=MAKEIPADDRESS(192,168,0,1); ipaddr->IPAddr = nIP; ipaddr->Enabled = true;
4、使用後,在FormClose事件中,釋放該控制項:
delete ipaddr;
5、TSysIPAddress32 封裝代碼:
//-------------------------------------------------------------// SysIPAddress.hpp//------------------------------------------------------------- #ifndef TSYSIPADDRESS32H#define TSYSIPADDRESS32H#include <vcl.h>#include <windows.h>class TSysIPAddress32 : public TWinControl{public: __property Text; __property Font; __property Enabled; __property TabStop; __property Handle; //__property Color = {default=0x292929}; __property bool IsEmpty = { read=_isEmpty }; __property int IPAddr = { read=_getIP, write=_setIP }; void ClearIP(void) { //清除IP控制項內容 IPM_CLEARADDRESS SendMessage(Handle,IPM_CLEARADDRESS,0,0); } __fastcall TSysIPAddress32(Classes::TComponent *AOwner) : TWinControl(AOwner) { Width = 150; Height = 22; Visible = true; TabStop = true; };protected: void __fastcall CreateParams(Controls::TCreateParams &Params) { TWinControl::CreateParams(Params); CreateSubClass(Params, "SysIPAddress32"); Params.Style |= WS_TABSTOP; }private: bool _isEmpty(void) { bool bret = false; if(SendMessage(Handle,IPM_ISBLANK,0,0)) { bret = true; } return bret; } int _getIP(void) { int nIP; //擷取IP值的32位整型變數值(IPM_GETADDRESS) SendMessage(Handle,IPM_GETADDRESS,0,int(&nIP)); return nIP; } void _setIP( int _ip ) { //設定IP控制項內容 IPM_SETADDRESS //nIP=MAKEIPADDRESS(192,168,0,1); SendMessage(Handle,IPM_SETADDRESS,0,_ip); } };#endif