在C++ Builder中使用系統自帶的IP地址編輯框。
1、BCB工程中,在需要使用IP地址框的窗體裡面。
首先引用頭文件,再申明變量。
[cpp]
#include "SysIPAddress.hpp"
TSysIPAddress32 *ipaddr;
2、在FormCreate事件中創建該控件,並指定位置:
[cpp]
ipaddr = new TSysIPAddress32(this);
ipaddr->Parent = this;
ipaddr->Left = 5;
ipaddr->Top = 5;
3、使用控件:
[cpp]
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事件中,釋放該控件:
[cpp]
delete ipaddr;
5、TSysIPAddress32 封裝代碼:
[cpp]
//-------------------------------------------------------------
// 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