IpAddress IP控件

ipaddressctrl.hpp
#ifndef ipaddressctrlH
#define ipaddressctrlH

namespace NSTS {

#include <windows.h>
#include <commctrl.h>
#include <string.h>
//#include <winsock2.h>

#pragma comment (lib, "ws2_32.lib")
#pragma comment (lib, "comctl32.lib")

class CIpAddressCtrl {
#define SELF_VALID IsWindow (m_hSelf)
public:
CIpAddressCtrl (void) {
m_hSelf = m_hParent = NULL;
};
~CIpAddressCtrl (void) {
if (SELF_VALID) {
Destroy ();
}

m_hSelf = m_hParent = NULL;
};

bool Init (HINSTANCE hInst, HWND hParent, const RECT* prc) {
if (prc == NULL) {
return false;
}

return Init (hInst, hParent, prc->left, prc->top, prc->right - prc->left, prc->bottom - prc->top);
};

bool Init (HINSTANCE hInst, HWND hParent, int iX, int iY, int iWidth, int iHeight) {
Destroy ();
if (hInst != NULL && IsWindow (hParent)) {
INITCOMMONCONTROLSEX icc;
icc.dwSize = sizeof (icc);
icc.dwICC = ICC_INTERNET_CLASSES;
InitCommonControlsEx (&icc);

m_hSelf = CreateWindowEx (0,
WC_IPADDRESS,
NULL,
WS_CHILD | WS_VISIBLE,
iX, iY, iWidth, iHeight,
hParent,
NULL,
hInst,
NULL);
if (m_hSelf == NULL) {
return false;
}

m_hParent = hParent;
return true;
}

return false;
};
void Destroy (void) {
if (SELF_VALID) {
DestroyWindow (m_hSelf);
m_hSelf = NULL;
}
m_hParent = NULL;
};
bool Attach (HWND hwnd) {
if (IsWindow (hwnd)) {
m_hSelf = hwnd;
m_hParent = ::GetParent (m_hSelf);
}
return false;
};

public:
bool GetIpAddress (char* pszIp) const {
if (pszIp != NULL) {
DWORD dwIp = 0;
if (GetIpAddress (&dwIp)) {
struct in_addr addr;
char* pszIpTemp = 0;
addr.S_un.S_addr = htonl (dwIp);
pszIpTemp = inet_ntoa (addr);
if (pszIpTemp) {
strcpy (pszIp, pszIpTemp);
} else {
strcpy (pszIp, "0.0.0.0");
}
return true;
}
}
return false;
};
bool GetIpAddress (DWORD* pdwIp) const {
if (SELF_VALID && pdwIp != NULL) {
SendMessage (m_hSelf, IPM_GETADDRESS, (WPARAM)0, (LPARAM)pdwIp);
return true;
}
return false;
};
bool SetIpAddress (const char* pszIp) {
if (pszIp) {
DWORD dwIp;
dwIp = inet_addr (pszIp);
return SetIpAddress (ntohl (dwIp));
}
return false;
};
bool SetIpAddress (BYTE b1, BYTE b2, BYTE b3, BYTE b4) {
return SetIpAddress (MAKEIPADDRESS (b1, b2, b3, b4));
};
bool SetIpAddress (DWORD dwIp) {
if (SELF_VALID) {
SendMessage (m_hSelf, IPM_SETADDRESS, (WPARAM)0, (LPARAM)dwIp);
return true;
}
return false;
};
bool Clear (void) {
if (SELF_VALID) {
SendMessage (m_hSelf, IPM_CLEARADDRESS, (WPARAM)0, (LPARAM)0);
return true;
}
return false;
};

HWND GetHwnd (void) const { return m_hSelf; };
HWND GetParent (void) const { return m_hParent; } ;

private:
HWND m_hSelf;
HWND m_hParent;
};

}

#endif // ipaddressctrlH

Usage:

NSTS::CIpAddressCtrl g_ip1, g_ip2;

WM_INITDIALOG:
g_ip1.Init (hInst, hwndDlg, 0, 0, 150, 20);
g_ip2.Attach (GetDlgItem (hwndDlg, IDC_IP1));

WM_COMMAND
IDC_GETIP:
{
char szIp [64] = {0};
g_ip1.GetIpAddress (szIp);
MessageBoxA (NULL, szIP, NULL, MB_OK);
}

IDC_SETIP:
{
g_ip1.SetIpAddress ("1.1.1.2");
}



posted @ 2012-01-31 00:54  夜雨無聲  阅读(1929)  评论(0编辑  收藏  举报