Click here to Skip to main content
15,896,522 members
Articles / Desktop Programming / MFC

EnetstatX

Rate me:
Please Sign up or sign in to vote.
4.42/5 (26 votes)
9 Jun 20041 min read 118K   4K   41  
Enhance netstat and packet filtering.
// ENetStatXDlg.cpp : implementation file
//

#include "stdafx.h"
#include "ENetStatX.h"
#include "ENetStatXDlg.h"


#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

//defines
#define ID_FAKE_CONTROL 0x9999

//init static members
	static UINT BASED_CODE indicators[] =
	{
		ID_INDICATOR_ERROR,
		ID_INDICATOR_TIME
	};	
	BOOL			 CENetStatXDlg::m_bFlagInit			 = FALSE;
	BOOL			 CENetStatXDlg::m_bFilterError		 = FALSE;
	int				 CENetStatXDlg::m_nItemFilter		 = -1;
	int				 CENetStatXDlg::m_nItemMain			 = -1;
	HANDLE			 CENetStatXDlg::m_hndLogConnEvent	 = NULL;
	int				 CENetStatXDlg::m_nNrOfConn			 = -1;
	CONNVIEW		 CENetStatXDlg::m_eConnView			 = viewAll;
	PMIB_TCPTABLE_EX CENetStatXDlg::m_pOldBuffTcpTableEx = NULL;
	CCriticalSection CENetStatXDlg::__CriticalSection__;
	DWORD			 CENetStatXDlg::ms_dwUpdateTime		 = 20 * 1000;

//implement out func
	DWORD WINAPI LogConn_ThreadProc(LPVOID lpParameter)
	{
		while (INFINITE)
		{
			if(CConnContainer::IsNewConnection())
			{
				//update table info
				::PostMessage((HWND)lpParameter, EVENT_TIMER_NEW_TCP_CONN, 0, 0);
			}
			else
			{
				//do nothing
			}

			Sleep(1000);
/*
			if (WAIT_OBJECT_0 == ::WaitForSingleObject(CENetStatXDlg::m_hndLogConnEvent, INFINITE))
			{
				::SendMessage((HWND)lpParameter, LOGMSG, 0, 0);
			}
*/
		}
		return 1;
	}

	DWORD WINAPI LogConn_ThreadProcUser(LPVOID lpParameter)
	{
		while (INFINITE)
		{
			if(CConnContainer::IsNewConnection())
				::SendMessage((HWND)lpParameter, EVENT_TIMER_REFRESH_LIST, 0, 0); //update table info

			Sleep(CENetStatXDlg::ms_dwUpdateTime);
			TRACE1("\n\t User update time : %d", CENetStatXDlg::ms_dwUpdateTime);
		}
		return 1;
	}


	VOID CALLBACK TcpNewConn_TimerProc(HWND hwnd, UINT uMsg, UINT_PTR idEvent,DWORD dwTime)	
	{
		//::SendMessage(hwnd, EVENT_TIMER_NEW_TCP_CONN, 0, 0);
	}

/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About
class CAboutDlg : public CDialog
{
	public:
		CAboutDlg();

	// Dialog Data
		//{{AFX_DATA(CAboutDlg)
		enum { IDD = IDD_ABOUTBOX };
		//}}AFX_DATA

		// ClassWizard generated virtual function overrides
		//{{AFX_VIRTUAL(CAboutDlg)
		protected:
		virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
		//}}AFX_VIRTUAL

	// Implementation
	protected:
		//{{AFX_MSG(CAboutDlg)
		//}}AFX_MSG
		DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
//
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
	//{{AFX_DATA_INIT(CAboutDlg)
	//}}AFX_DATA_INIT
}
/////////////////////////////////////////////////////////////////////////////
//
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAboutDlg)
	//}}AFX_DATA_MAP
}
/////////////////////////////////////////////////////////////////////////////
//
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
	//{{AFX_MSG_MAP(CAboutDlg)
		// No message handlers
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CENetStatXDlg dialog
CENetStatXDlg::CENetStatXDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CENetStatXDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CENetStatXDlg)
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDI_ICON_APP);

	m_pTcp			 = new CTCPTable();
	m_pUdp			 = new CUDPClass();
	m_pFilter		 = new CFilter();
	m_pSniff		 = new CSniff();
	
	m_pImageListMain = NULL;
	m_bFocus		 = true;	

	m_hndThUser		 = NULL;
	m_hndTh			 = NULL;
}
/////////////////////////////////////////////////////////////////////////////////
//
void CENetStatXDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CENetStatXDlg)
	DDX_Control(pDX, IDC_LIST_Filter, m_ListFilter);
	DDX_Control(pDX, IDC_LIST_Main, m_ListMain);
	//}}AFX_DATA_MAP
}
/////////////////////////////////////////////////////////////////////////////////
//
BEGIN_MESSAGE_MAP(CENetStatXDlg, CDialog)
	//{{AFX_MSG_MAP(CENetStatXDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_WM_TIMER()
	ON_COMMAND(ID_Menu_About, OnMenuAbout)
	ON_NOTIFY(NM_DBLCLK, IDC_LIST_Filter, OnDblclkLISTFilter)
	ON_NOTIFY(NM_DBLCLK, IDC_LIST_Main, OnDblclkLISTMain)
	ON_COMMAND(ID_FILE_REFRESH_1S, OnFileRefresh1s)
	ON_COMMAND(ID_FILE_REFRESH_10S, OnFileRefresh10s)
	ON_COMMAND(ID_FILE_REFRESH_20S, OnFileRefresh20s)
	ON_COMMAND(ID_FILE_REFRESH_5S, OnFileRefresh5s)
	ON_COMMAND(ID_FILE_REFRESH_60S, OnFileRefresh60s)
	ON_COMMAND(ID_FILE_REFRESH_NOWF5, OnFileRefreshNowf5)
	ON_COMMAND(ID_FILE_REFRESH_STOP, OnFileRefreshStop)
	ON_COMMAND(ID_CONNECTIONS_VIEW_ALL, OnConnectionsViewAll)
	ON_COMMAND(ID_CONNECTIONS_VIEW_CONNECTED, OnConnectionsViewConnected)
	ON_COMMAND(ID_SNIFF_ENABLE, OnSniffEnable)
	ON_COMMAND(ID_SNIFF_DISABLE, OnSniffDisable)
	ON_COMMAND(IDR_MENU_POP_FILTER_SET, OnMenuPopFilterSet)
	ON_COMMAND(ID_FILTER_FILTER_RESET, OnFilterFilterReset)
	ON_COMMAND(ID_FILTER_FILTER_MODIFY, OnFilterFilterModify)
	ON_NOTIFY(NM_RCLICK, IDC_LIST_Filter, OnRclickLISTFilter)
	ON_COMMAND(ID_FILTER_FILTER_DELETE, OnFilterFilterDelete)
	ON_COMMAND(ID_FILTER_FILTER_VIEWLOG, OnFilterFilterViewlog)
	ON_NOTIFY(LVN_KEYDOWN, IDC_LIST_Main, OnKeydownLISTMain)
	ON_COMMAND(ID_FILTERSNIFF_ENABLE, OnFiltersniffEnable)
	ON_MESSAGE(LOGMSG, OnLogMsg)
	ON_MESSAGE(EVENT_TIMER_NEW_TCP_CONN, OnTcpNewConnMsg)
	ON_MESSAGE(EVENT_TIMER_REFRESH_LIST, OnUpdateList)
	ON_MESSAGE(WM_ICON_NOTIFY, OnTrayNotification)
	ON_COMMAND(ID_TRAY_EXIT, OnTrayExit)
	ON_COMMAND(ID_TRAY_RESTORE, OnTrayRestore)
	ON_NOTIFY(NM_RCLICK, IDC_LIST_Main, OnRclickLISTMain)
	ON_COMMAND(ID_SYS_KILLPROCESS, OnSysKillprocess)
	ON_COMMAND(ID_SYS_CLOSECONNECTION, OnSysCloseConnection)
	ON_WM_SIZE()
	ON_WM_SIZING()
	//}}AFX_MSG_MAP
	END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// 
BEGIN_EASYSIZE_MAP(CENetStatXDlg)
	EASYSIZE(IDC_LIST_Main,			ES_BORDER, ES_BORDER, ES_BORDER, IDC_LIST_Filter, 0);
	EASYSIZE(IDC_LIST_Filter,		ES_BORDER, IDC_LIST_Main, ES_BORDER, ES_BORDER, 0);
END_EASYSIZE_MAP

/////////////////////////////////////////////////////////////////////////////
// CENetStatXDlg message handlers
BOOL CENetStatXDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	
	//**********************************************************************
	// TODO: Add extra initialization here
	////////////////////////////////////////////////////////////////////////
	//	
	
	// Create and show the splash screen.
	CSplashWnd::ShowSplashScreen(3000, IDB_SPLASH, this);

	m_sFilter.dwProto = 0;
	m_sFilter.eAction = PF_ACTION_FORWARD;
	m_sFilter.eInOut = in;
	m_sFilter.strLocalAddress = "0.0.0.0";
	m_sFilter.strRemoteAddress = "0.0.0.0";
	m_sFilter.ulLocalPort = 0;
	m_sFilter.ulRemotePort = 0;

	//init thread and event log
	InitCriticalSection();

	//init taskbarnotifier
	m_ctrlTaskBarIn.Create(this);
	m_ctrlTaskBarIn.SetSkin(IDB_BITMAP_TOOLTIP_IN, 255, 0, 255);
	//m_ctrlTaskBarIn.SetSkin("F:\\MyProjects\\ENetStatX\\res\\tooltip_in.bmp",255,0,255);
	m_ctrlTaskBarIn.SetTextFont("Verdana",80,TN_TEXT_NORMAL, TN_TEXT_BOLD);
	m_ctrlTaskBarIn.SetTextColor(RGB(0,0,0), RGB(255,255,255));
	m_ctrlTaskBarIn.SetTextRect(CRect(
			10, //left
			0, //top
			m_ctrlTaskBarIn.m_nSkinWidth-10, //right
			m_ctrlTaskBarIn.m_nSkinHeight-15)); //bottom
	m_ctrlTaskBarIn.SetTransparent(90); //default 58

	//init taskbarnotifier
	m_ctrlTaskBarOut.Create(this);
	m_ctrlTaskBarOut.SetSkin(IDB_BITMAP_TOOLTIP_OUT, 255, 0, 255);
	//m_ctrlTaskBarOut.SetSkin("F:\\MyProjects\\ENetStatX\\res\\tooltip_out.bmp",255,0,255);
	m_ctrlTaskBarOut.SetTextFont("Verdana",80,TN_TEXT_NORMAL, TN_TEXT_BOLD);
	m_ctrlTaskBarOut.SetTextColor(RGB(0,0,0), RGB(255,255,255));
	m_ctrlTaskBarOut.SetTextRect(CRect(
			10,
			0,
			m_ctrlTaskBarOut.m_nSkinWidth-10,
			m_ctrlTaskBarOut.m_nSkinHeight-15));
	m_ctrlTaskBarOut.SetTransparent(90); //default 58
	
	//init control
	InitCtrlList();

	//Create a splitter bar
	CRect rect;
	m_ctrlSplitterBar.Create(WS_DLGFRAME|WS_VISIBLE, rect, this, ID_FAKE_CONTROL, TRUE);
	m_ctrlSplitterBar.SetPanes(&m_ListMain, &m_ListFilter);

	//init conn map
	CList<INTERFACE_HANDLE, INTERFACE_HANDLE&> m_ListHInterf(128);
	m_MapNewTcpConn.InitHashTable(257);
	m_MapHInterf.InitHashTable(257);

	//create status bar
	m_bar.Create(this); //We create the status bar
	m_bar.SetIndicators(indicators,2); //Set the number of panes 

	CRect sb_rect;
	GetClientRect(&sb_rect);
	//Size the two panes
	m_bar.SetPaneInfo(0,ID_INDICATOR_ERROR,SBPS_NORMAL,sb_rect.Width()-100);      
	m_bar.SetPaneInfo(1,ID_INDICATOR_TIME,SBPS_STRETCH ,0);

	//This is where we actually draw it on the screen
	RepositionBars(AFX_IDW_CONTROLBAR_FIRST,AFX_IDW_CONTROLBAR_LAST,ID_INDICATOR_TIME);

	//m_bar.GetStatusBarCtrl().SetBkColor(RGB(200,200,200));
	
	//TrayIcon
	if (!m_TrayIcon.Create(this, WM_ICON_NOTIFY, "ENetStat ...", m_hIcon, IDR_MENU_TRAY))
		return FALSE;
	else
		m_TrayIcon.HideIcon();

	//Init
	InitListAll();
	OnFileRefresh20s();
	
	//add layout resize
	INIT_EASYSIZE;

	return TRUE;  // return TRUE  unless you set the focus to a control
}
/////////////////////////////////////////////////////////////////////////////
//
void CENetStatXDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	DWORD dwExitCode = 0;
	BOOL bRez = false;

	switch (nID)
	{
		case SC_MINIMIZE:
			ShowWindow(SW_HIDE);
			m_TrayIcon.ShowIcon();
			m_bFocus = false;
		return;

		case SC_CLOSE:
			
			SuspendThread(m_hndTh);
			SuspendThread(m_hndThUser);

			bRez = GetExitCodeThread(m_hndTh, &dwExitCode);
			bRez = TerminateThread(m_hndTh, dwExitCode);
			bRez = GetExitCodeThread(m_hndThUser, &dwExitCode);
			bRez = TerminateThread(m_hndThUser, dwExitCode);

			SendMessage(WM_CLOSE);
		return;


		default:
		break;
	}

	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}
/////////////////////////////////////////////////////////////////////////////////
//
// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CENetStatXDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}
/////////////////////////////////////////////////////////////////////////////////
//
// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CENetStatXDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}
/////////////////////////////////////////////////////////////////////////////////
//
void CENetStatXDlg::ReleaseMembers()
{
	//remove filters
	if (m_ListHInterf.IsEmpty() == FALSE)
	{
		POSITION pos = m_ListHInterf.GetHeadPosition();
		int i = m_ListHInterf.GetCount();
		
		do 
		{
			m_pFilter->RemoveFilter(m_ListHInterf.GetNext(pos));
			i--;
		}
		while(i > 0);
	}
}
/////////////////////////////////////////////////////////////////////////////////
//
void CENetStatXDlg::InitCtrlList()
{
	// Init ImageList for m_ListMain
	CWinApp *pApp = AfxGetApp();
	m_pImageListMain = new CImageList();
	ASSERT(m_pImageListMain != NULL);    // serious allocation failure checking
	BOOL brez = m_pImageListMain->Create(16, 16, ILC_COLOR32, 16, 64);
	m_pImageListMain->SetBkColor(CLR_DEFAULT);
	m_pImageListMain->Add(pApp->LoadIcon(IDI_ICON_PROTO));
	m_pImageListMain->Add(pApp->LoadIcon(IDI_ICON_UNK_PROCESS));
	m_ListMain.SetImageList(m_pImageListMain, LVSIL_SMALL);	

	//set style of the list
	m_ListMain.SetExtendedStyle(LVS_EX_SUBITEMIMAGES | LVS_EX_HEADERDRAGDROP | LVS_EX_FULLROWSELECT | LVS_EDITLABELS);

	// Init ListView
	m_ListMain.InsertColumn(hProto,			"Proto",		 LVCFMT_LEFT, 60,  -1) ;
	m_ListMain.InsertColumn(hPid,			"Pid",			 LVCFMT_LEFT, 40,  -1) ;
	m_ListMain.InsertColumn(hProcessName,	"Process Name",  LVCFMT_LEFT, 100, -1) ;
	m_ListMain.InsertColumn(hLocalAddress,	"Local Address", LVCFMT_LEFT, 100, -1) ;
	m_ListMain.InsertColumn(hLocalPort,		"Local Port",	 LVCFMT_LEFT, 80,  -1) ;
	m_ListMain.InsertColumn(hRemoteAddress, "Remote Address",LVCFMT_LEFT, 100, -1) ;
	m_ListMain.InsertColumn(hRemotePort,	"Remote Port",	 LVCFMT_LEFT, 80,  -1) ;
	m_ListMain.InsertColumn(hState,			"State",		 LVCFMT_LEFT, 100, -1) ;

	//set style of the list
	// Init ImageList
	CImageList *m_pImageList = new CImageList();
	ASSERT(m_pImageList != NULL);    // serious allocation failure checking
	brez = m_pImageList->Create(16, 16, ILC_COLOR24, 6, 6);
	m_pImageList->SetBkColor(CLR_DEFAULT);
	m_pImageList->Add(pApp->LoadIcon(IDI_ICON_DEFAULT));
	m_pImageList->Add(pApp->LoadIcon(IDI_ICON_PROTO));
	m_pImageList->Add(pApp->LoadIcon(IDI_ICON_INACTIVE));
	m_pImageList->Add(pApp->LoadIcon(IDI_ICON_ACTIVE));
	m_pImageList->Add(pApp->LoadIcon(IDI_ICON_IN));
	m_pImageList->Add(pApp->LoadIcon(IDI_ICON_OUT));
	m_ListFilter.SetImageList(m_pImageList, LVSIL_SMALL);	

	m_ListFilter.SetExtendedStyle(LVS_EX_SUBITEMIMAGES | LVS_EX_HEADERDRAGDROP | LVS_EX_FULLROWSELECT | LVS_EDITLABELS);

	// Init ListView
	m_ListFilter.InsertColumn(hfHeaderInfo,		" ",			  LVCFMT_LEFT, 20,  -1) ;
	m_ListFilter.InsertColumn(hfProto,			"Proto",		  LVCFMT_LEFT, 40,  -1) ;
	m_ListFilter.InsertColumn(hfAction,			"Action",		  LVCFMT_LEFT, 60,  -1) ;
	m_ListFilter.InsertColumn(hfDir,			"Dir",			  LVCFMT_LEFT, 80,  -1) ;
	m_ListFilter.InsertColumn(hfLocalAddress,	"Local Address",  LVCFMT_LEFT, 100, -1) ;
	m_ListFilter.InsertColumn(hfLocalPort,		"Local Port",	  LVCFMT_LEFT, 80,  -1) ;
	m_ListFilter.InsertColumn(hfRemoteAddress,	"Remote Address", LVCFMT_LEFT, 100, -1) ;
	m_ListFilter.InsertColumn(hfRemotePort,		"Remote Port",	  LVCFMT_LEFT, 80,  -1) ;
	m_ListFilter.InsertColumn(hfState,			"State",		  LVCFMT_LEFT, 100, -1) ;
}
/////////////////////////////////////////////////////////////////////////////////
//
int CENetStatXDlg::UpdateIncommingConn()
{
	//get parameters from buff packet
	BYTE		Proto		 = 0;
	u_short		ulRawPackLen = 0;
	u_short		ulRawLocPort = 0;
	u_short		ulRawRemPort = 0;
	TCPTABLE	sTcpTable;
	UDPTABLE	sUdpTable;

	if (FALSE == m_pSniff->RetreiveDataConn(&Proto, &ulRawPackLen, &ulRawLocPort, &ulRawRemPort))
	{
		TRACE("\nError, RetreiveDataConn()");
		return -1;
	}

	switch(Proto)
	{
		case IPPROTO_ICMP:
			TRACE("\nInfo, ICMP");
		break;

		case IPPROTO_TCP:
			//map, the key is the local port
			sTcpTable.strConnectionState = "";
			sTcpTable.strLocalAddress = "";
			sTcpTable.strProcessName = "";
			sTcpTable.strRemoteAddress = "";
			//sTcpTable.ulDataAmmount = ulRawPackLen;
			sTcpTable.ulLocalPort = ulRawLocPort;
			sTcpTable.ulRemotePort = ulRawRemPort;	

		break;

		case IPPROTO_UDP:
			sUdpTable.strLocalAddress = "";
			sUdpTable.strProcessName = "";
			sUdpTable.ulDataAmmount = ulRawPackLen;
			sUdpTable.ulLocalPort = ulRawLocPort;
		break;

		default:
			//do nothing
		break;
	}

	return -1;
}
/////////////////////////////////////////////////////////////////////////////////
//
LRESULT CENetStatXDlg::OnUpdateList(WPARAM wParam, LPARAM lParam)
{
	InitListAll();	return 1;
}
/////////////////////////////////////////////////////////////////////////////////
//
LRESULT CENetStatXDlg::OnTcpNewConnMsg(WPARAM wParam, LPARAM lParam)
{
	return DetectNewConn();
}
/////////////////////////////////////////////////////////////////////////////////
//
bool CENetStatXDlg::DetectNewConn()
{
	// let's ask some privacy
	__CriticalSection__.Lock();

	TCPTABLE	sTcpTable;
	in_addr		stAddr;
	DWORD		dwRez		= 0;

	// init tcp table
	if (m_pTcp == NULL) return false;
	if (NO_ERROR != (dwRez = m_pTcp->GetTableEx()))	return false;
		
	/**********************Get TCP info**********************/
	for (DWORD i = 0; i < m_pTcp->GetNumberOfEntries(); i++)
	{
		stAddr.s_addr				 = static_cast<u_long>(m_pTcp->GetLocalAddress(i));
		sTcpTable.strLocalAddress	 = inet_ntoa(stAddr);
		sTcpTable.ulLocalPort		 = ntohs(static_cast<u_short>(m_pTcp->GetLocalPort(i)));
		stAddr.s_addr				 = static_cast<u_long>(m_pTcp->GetRemoteAddress(i));
		sTcpTable.strRemoteAddress	 = inet_ntoa(stAddr);
		sTcpTable.ulRemotePort		 = ntohs(static_cast<u_short>(m_pTcp->GetRemotePort(i)));
		sTcpTable.dwPid				 = m_pTcp->GetProcessId(i);
		sTcpTable.strProcessName	 = m_pTcp->GetProcById(sTcpTable.dwPid);
		sTcpTable.strConnectionState = m_pTcp->Convert2State(m_pTcp->GetElement(i).dwState);

		//check present conn state
		if (sTcpTable.strConnectionState == "ESTABLISHED")
		{
			CString strLP(L"");
			CString strRP(L"");
			TCPTABLE sTcpTableOut;
			
			//is there already stored this outgoing connection?
 			if (0 == m_MapNewTcpConn.Lookup(sTcpTable.ulLocalPort, sTcpTableOut))
			{
				//can happen on any local port allocated by the OS(it will be random allocated)
				//new outgoing conn
				m_MapNewTcpConn.SetAt(sTcpTable.ulLocalPort, sTcpTable);
				
				//tooltip info
				strLP.Format(TEXT("%u"), sTcpTable.ulLocalPort);
				strRP.Format(TEXT("%u"), sTcpTable.ulRemotePort);
				m_ctrlTaskBarOut.Show("\n\n\n OUT remote address: " + sTcpTable.strRemoteAddress + \
								      "\n on remote port: " + strRP + \
								      "\n process: " + sTcpTable.strProcessName);

				InitListAll();
				return true;
			}

			else //if state has changed (be aware the connection already exist in the map)
			{					
				if ((sTcpTableOut.strConnectionState != sTcpTable.strConnectionState) || \
					(sTcpTableOut.strRemoteAddress != sTcpTable.strRemoteAddress))
				{
					//update conn
					m_MapNewTcpConn.SetAt(sTcpTable.ulLocalPort, sTcpTable);
					
					//tooltip info
					strLP.Format(TEXT("%u"), sTcpTable.ulLocalPort);
					strRP.Format(TEXT("%u"), sTcpTable.ulRemotePort);
					m_ctrlTaskBarIn.Show("\n\n\n IN remote address: " + sTcpTable.strRemoteAddress + \
									     "\n on local port: " + strLP + \
								         "\n process: " + sTcpTable.strProcessName);

					InitListAll();
					return true;
				}
			}
		}
	}

	return false;

	__CriticalSection__.Unlock();
}
/////////////////////////////////////////////////////////////////////////////////
//
void CENetStatXDlg::InitListTcpEx(bool exclusive) //exclude "127.0.0.1" & "0.0.0.0"
{
	TCPTABLE	sTcpTable;
	in_addr		stAddr;
	CString		strText(L"");
	DWORD		iItem = 0;

	//clean list
	m_ListMain.SetRedraw(FALSE);
	if (exclusive)
	{
		m_ListMain.DeleteAllItems();
		iItem = 0;
	}
	else
	{
		iItem = m_ListMain.GetItemCount();
	}

	/**********************Get TCP info**********************/
	//fill buffer
	DWORD	dwRez = 0;

	// init tcp table
	if (m_pTcp == NULL) return;
	if (NO_ERROR != (dwRez = m_pTcp->GetTableEx()))	return;

	//print the info
	int iSubItem = 1;
	for (DWORD i = 0; i < m_pTcp->GetNumberOfEntries(); i++)
	{
		//prepare the local address field
		stAddr.s_addr = static_cast<u_long>(m_pTcp->GetLocalAddress(i));
		sTcpTable.strLocalAddress = inet_ntoa(stAddr);
		
		//prepare the local port field
		sTcpTable.ulLocalPort = ntohs(static_cast<u_short>(m_pTcp->GetLocalPort(i)));

		//prepare the remote address field
		stAddr.s_addr = static_cast<u_long>(m_pTcp->GetRemoteAddress(i));
		sTcpTable.strRemoteAddress = inet_ntoa(stAddr);

		//prepare the remote port field
		sTcpTable.ulRemotePort = ntohs(static_cast<u_short>(m_pTcp->GetRemotePort(i)));

		//prepare the Pid
		sTcpTable.dwPid = m_pTcp->GetProcessId(i);
		sTcpTable.strProcessName = m_pTcp->GetProcById(sTcpTable.dwPid);

		//prepare the state
		sTcpTable.strConnectionState = m_pTcp->Convert2State(m_pTcp->GetState(i));
	
		if (sTcpTable.strConnectionState == "ESTABLISHED")
		{
			//print TCP info
			m_ListMain.InsertItem(iItem, "TCP");
			LVITEM item;
			item.mask = LVIF_TEXT | LVIF_IMAGE;
			item.iItem = iItem;
			item.pszText = "TCP";
			item.iSubItem = hProto;
			item.iImage = GetProcessIcon(sTcpTable.strProcessName, m_pTcp->GetProcPath(sTcpTable.dwPid));
			m_ListMain.SetItem(&item);

			//print info for locals
			strText.Format(TEXT("%d"), sTcpTable.dwPid);
			m_ListMain.SetItemText(iItem, hPid, strText);
			
			//proc icon			
			m_ListMain.SetItemText(iItem, hProcessName, sTcpTable.strProcessName);
			m_ListMain.SetItemText(iItem, hLocalAddress, sTcpTable.strLocalAddress);
			strText.Format(TEXT("%u"), sTcpTable.ulLocalPort);
			m_ListMain.SetItemText(iItem, hLocalPort, strText);

			//print info for remote
			m_ListMain.SetItemText(iItem,hRemoteAddress, sTcpTable.strRemoteAddress);

			//print info for state
			m_ListMain.SetItemText(iItem, hState, sTcpTable.strConnectionState);

			if (sTcpTable.strConnectionState == "ESTABLISHED")
			{
				strText.Format(TEXT("%u"), sTcpTable.ulRemotePort);
				m_ListMain.SetItemText(iItem, hRemotePort, strText);
			}
			else
			{
				m_ListMain.SetItemText(iItem, hRemotePort, "-");			
			}

			iItem ++; //set the next entry
		} //end if established state
	}//end for

	m_ListMain.SetRedraw(TRUE);
	
}
/////////////////////////////////////////////////////////////////////////////////
//
void CENetStatXDlg::InitListUdpEx(bool exclusive) //exclude "127.0.0.1" & "0.0.0.0"
{
	UDPTABLE sUdpTable;
	in_addr stAddr;
	CString strText(L"");
	DWORD	iItem = 0;

	//clean list
	m_ListMain.SetRedraw(FALSE);
	if (exclusive)
	{
		m_ListMain.DeleteAllItems();
		iItem = 0;
	}
	else
	{
		iItem = m_ListMain.GetItemCount();
	}

	/**********************Get UDP info**********************/
	//fill buffer
	m_pUdp->GetTableEx();

	//print the info
	int iSubItem = 1;
	for (DWORD i = 0; i < m_pUdp->m_pBuffUdpTableEx->dwNumEntries; i++)
	{
		//prepare the local address field
		stAddr.s_addr = static_cast<u_long>(m_pUdp->m_pBuffUdpTableEx->table[i].dwLocalAddr);;
		sUdpTable.strLocalAddress = inet_ntoa(stAddr);
		
		//prepare the local port field
		sUdpTable.ulLocalPort = ntohs(static_cast<u_short>(m_pUdp->m_pBuffUdpTableEx->table[i].dwLocalPort));

		//prepare the Pid
		sUdpTable.dwPid = m_pUdp->m_pBuffUdpTableEx->table[i].dwProcessId;
		sUdpTable.strProcessName = m_pUdp->GetProcById(sUdpTable.dwPid);
	
		//if ((sUdpTable.strLocalAddress != "0.0.0.0") && (sUdpTable.strLocalAddress != "127.0.0.1"))
		{
			//print TCP info
			m_ListMain.InsertItem(iItem, "UDP");

			//proc icon
			LVITEM item;
			item.mask = LVIF_TEXT | LVIF_IMAGE;
			item.iItem = iItem;
			item.iSubItem = hProto;
			item.iImage = GetProcessIcon(sUdpTable.strProcessName, m_pTcp->GetProcPath(sUdpTable.dwPid));
			m_ListMain.SetItem(&item);

			//print info for locals
			strText.Format(TEXT("%d"), sUdpTable.dwPid);
			m_ListMain.SetItemText(iItem, hPid, strText);
						
			m_ListMain.SetItemText(iItem, hProcessName, sUdpTable.strProcessName);

			m_ListMain.SetItemText(iItem, hLocalAddress, sUdpTable.strLocalAddress);

			strText.Format(TEXT("%u"), sUdpTable.ulLocalPort);
			m_ListMain.SetItemText(iItem, hLocalPort, strText);

			//print info for remote and state
			m_ListMain.SetItemText(iItem,hRemoteAddress, "-");
			m_ListMain.SetItemText(iItem,hRemotePort, "-");
			m_ListMain.SetItemText(iItem,hState, "-");

			iItem ++; //set the next entry
		} //end if real ip
	}//end for

	m_ListMain.SetRedraw(TRUE);
	
}
/////////////////////////////////////////////////////////////////////////////////
//
void CENetStatXDlg::InitListAll()
{
	if (m_eConnView == viewConnected)
	{
		InitListTcpEx(true);
		return;
	}

	in_addr stAddr;
	char	strLocAddress[16];
	char	strRemAddress[16];
	CString strText(L"");
	DWORD	iItem;
	LVITEM  item;

	//clean list
	m_ListMain.SetRedraw(FALSE);
	m_ListMain.DeleteAllItems();

	/**********************Get TCP info**********************/
	//fill buffer
	DWORD	dwRez = 0;

	// init tcp table
	if (m_pTcp == NULL) return;
	if (NO_ERROR != (dwRez = m_pTcp->GetTableEx()))	return;

	//print the info
	int iSubItem = 1;
	for (iItem = 0; iItem < m_pTcp->GetNumberOfEntries(); iItem++)
	{
			//prepare the local address field
			u_long ulLocalAddress = static_cast<u_long>(m_pTcp->GetLocalAddress(iItem));
			stAddr.s_addr = ulLocalAddress;
			strcpy(strLocAddress, inet_ntoa(stAddr));
		
			//prepare the local port field
			u_short usLocalPort = ntohs(static_cast<u_short>(m_pTcp->GetLocalPort(iItem)));

			//prepare the remote address field
			u_long ulRemoteAddress = static_cast<u_long>(m_pTcp->GetRemoteAddress(iItem));
			stAddr.s_addr = ulRemoteAddress;
			strcpy(strRemAddress, inet_ntoa(stAddr));

			//prepare the remote port field
			u_short usRemotePort = ntohs(static_cast<u_short>(m_pTcp->GetRemotePort(iItem)));

			//prepare the Pid
			DWORD dwPid = m_pTcp->GetProcessId(iItem);
			CString strProcName = m_pTcp->GetProcById(dwPid);

			//print TCP info
			if ("TCP" != m_ListMain.GetItemText(iItem, hProto))
			m_ListMain.InsertItem(iItem, "TCP");
			
			//print info for locals
			strText.Format(TEXT("%d"), dwPid);
			m_ListMain.SetItemText(iItem, hPid, strText);
						
			//proc icon
			//LVITEM item;
			item.mask = LVIF_TEXT | LVIF_IMAGE;
			item.iItem = iItem;
			item.iSubItem = hProto; //hProcessName;
			item.pszText = "TCP"; //to be ignored
			int iIcoIndex = -1;
			iIcoIndex = GetProcessIcon(strProcName, m_pTcp->GetProcPath(dwPid));
			item.iImage = iIcoIndex;
			m_ListMain.SetItem(&item);
			strText.Format(TEXT("%s"), strProcName);
			m_ListMain.SetItemText(iItem, hProcessName, strText);

			strText.Format(TEXT("%s"), strLocAddress);
			m_ListMain.SetItemText(iItem, hLocalAddress, strText);

			strText.Format(TEXT("%u"), usLocalPort);
			m_ListMain.SetItemText(iItem, hLocalPort, strText);

			//print info for remote
			strText.Format(TEXT("%s"), strRemAddress);
			m_ListMain.SetItemText(iItem,hRemoteAddress, strText);

			//print info for state
			strText.Format(TEXT("%s"), m_pTcp->Convert2State(m_pTcp->m_pBuffTcpTableEx->table[iItem].dwState));
			m_ListMain.SetItemText(iItem,hState, strText);

			if (m_pTcp->m_pBuffTcpTableEx->table[iItem].dwState == MIB_TCP_STATE_ESTAB)
			{
				strText.Format(TEXT("%u"), usRemotePort);
				m_ListMain.SetItemText(iItem, hRemotePort, strText);
			}
			else
			{
				strText = "-";
				m_ListMain.SetItemText(iItem, hRemotePort, strText);			
			}
	}

	/**********************Get UDP info**********************/
	in_addr _stAddr;
	char	_strLocAddress[16];
	u_long	_ulLocalAddress = 0;
	u_short _usLocalPort = 0;
	DWORD	_dwPid = 0;
	CString _strProcName (L"");
	int		_iSubItem = 1;
	
	//fill buffer
	m_pUdp->GetTableEx();

	//print the info
	for (DWORD _iItem = 0; _iItem < m_pUdp->m_pBuffUdpTableEx->dwNumEntries; _iItem++)
	{
		//prepare the local address field
		_ulLocalAddress = static_cast<u_long>(m_pUdp->m_pBuffUdpTableEx->table[_iItem].dwLocalAddr);
		_stAddr.s_addr = _ulLocalAddress;
		strcpy(_strLocAddress, inet_ntoa(_stAddr));

		//prepare the local port field
		_usLocalPort = ntohs(static_cast<u_short>(m_pUdp->m_pBuffUdpTableEx->table[_iItem].dwLocalPort));

		//prepare the Pid
		_dwPid = m_pUdp->m_pBuffUdpTableEx->table[_iItem].dwProcessId;

		_strProcName = m_pUdp->GetProcById(m_pUdp->m_pBuffUdpTableEx->table[_iItem].dwProcessId);

		//print UDP info
		if ("UDP" != m_ListMain.GetItemText(iItem, hProto))
		m_ListMain.InsertItem(iItem, "UDP");

		//print info for locals
		strText.Format(TEXT("%d"), _dwPid);
		m_ListMain.SetItemText(iItem,hPid, strText);

		//proc icon
		//LVITEM item;
		item.mask = LVIF_TEXT | LVIF_IMAGE;
		item.iItem = iItem;
		item.iSubItem = hProto;//hProcessName;
		item.pszText = "UDP"; //to be ignored
		int _iIcoIndex = GetProcessIcon(_strProcName, m_pTcp->GetProcPath(_dwPid));
		item.iImage = _iIcoIndex;
		m_ListMain.SetItem(&item);
		strText.Format(TEXT("%s"), _strProcName);
		m_ListMain.SetItemText(iItem, hProcessName, strText);

		strText.Format(TEXT("%s"), _strLocAddress);
		m_ListMain.SetItemText(iItem,hLocalAddress, strText);

		strText.Format(TEXT("%u"), _usLocalPort);
		m_ListMain.SetItemText(iItem,hLocalPort, strText);


		//print info for remote
		m_ListMain.SetItemText(iItem,hRemoteAddress, "-");
		m_ListMain.SetItemText(iItem,hRemotePort, "-");

		
		//print info for state
		m_ListMain.SetItemText(iItem,hState, "-");

		iItem++;
	}

	m_ListMain.SetRedraw(TRUE);
}
/////////////////////////////////////////////////////////////////////////////////
//
LRESULT CENetStatXDlg::WindowProc(UINT message, WPARAM wParam, LPARAM lParam) 
{
	int iRez = SOCKET_ERROR;
	int iAmountData = 0;
	
	switch(message)
	{
		case WM_CLOSE:
			ReleaseMembers();
		break;

		case WM_SOCKEVENT:
		{
			if (WSAGETSELECTERROR(lParam)) 
			{	
				m_bFlagInit = m_pSniff->Clean(this->m_hWnd); 
				return 0;				  // Exit
			}

		    switch (WSAGETSELECTEVENT(lParam))  // Differentiate between the events
			{	 
				case FD_READ:
				{	
					memset(m_pSniff->m_ucPacketOnes, 0x00, sizeof(m_pSniff->m_ucPacketOnes));
					memset(m_pSniff->m_ucPacket, 0x00, sizeof(m_pSniff->m_ucPacket));

					// Receive data until EOT
					do
					{
						//assume that the notify event is focused an a single conn, no multiple conn receive during one event notification						
						iRez = recv(m_pSniff->m_hSniffSocket, (char FAR*)m_pSniff->m_ucPacketOnes, sizeof(m_pSniff->m_ucPacketOnes), 0);
						if ((iRez > 0) || (iRez != SOCKET_ERROR))
						{
							memcpy(m_pSniff->m_ucPacket, m_pSniff->m_ucPacketOnes, sizeof(m_pSniff->m_ucPacketOnes));
							
							//TRACE1("\nOnes buffer len: %d", iRez);
							iAmountData += iRez;

							UpdateIncommingConn();
						}
					}
					while(iRez != SOCKET_ERROR);

					//TRACE1("\nTotal buffer len: %d", iAmountData);
				}	
				break;

				case FD_WRITE:
				// Write data
					TRACE("\nWrite Data");
				break;
        
				case FD_CONNECT:
				// Just connected to server
					TRACE("\nConnect");
				break;
        
				default:
				break;
			}
		    
			break;
		}
		
		default:
		break;
	}
	return CDialog::WindowProc(message, wParam, lParam);
}
/////////////////////////////////////////////////////////////////////////////////
//
void CENetStatXDlg::OnTimer(UINT nIDEvent) 
{
	/*
	switch(nIDEvent)
	{
		case EVENT_TIMER_REFRESH_LIST:
			InitListAll();
		break;

		case EVENT_TIMER:
			InitListAll();	
		break;

		case EVENT_TIMER_NEW_TCP_CONN:
			DetectNewConn();
		break;

		default:
			//do nothing
		break;
	}
	*/

	CDialog::OnTimer(nIDEvent);
}
/////////////////////////////////////////////////////////////////////////////////
//
void CENetStatXDlg::OnMenuAbout() 
{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();	
}
/////////////////////////////////////////////////////////////////////////////////
//
bool CENetStatXDlg::AddFilter2List()
{
	if (m_bFilterError == TRUE)
		return false;

	int		iItem	  = 0;
	CString strProto  (L"");
	CString strDir	  (L"");
	CString strWork	  (L"");

	switch(m_sFilter.eInOut)
	{
		case in:
			strDir = "IN";
		break;

		default:
		case out:
			strDir = "OUT";
		break;
	}

	switch(m_sFilter.dwProto)
	{
		case IPPROTO_TCP:
			strProto = "TCP";
		break;

		default:
		case IPPROTO_UDP:
			strProto = "UDP";
		break;
	}


	iItem = m_ListFilter.GetItemCount();
	
	LVITEM item;
	item.mask = LVIF_TEXT | LVIF_IMAGE;
	item.iItem = iItem;
	item.iSubItem = hfDir;

	//add info filter
	m_ListFilter.InsertItem(iItem, " ");
	
	m_ListFilter.SetItemText(iItem, hfProto, strProto);

	m_ListFilter.SetItemText(iItem, hfAction, "Block");

    item.pszText = "OUT";	
    item.iImage = static_cast<int>(icoOut);
    m_ListFilter.SetItem(&item);	

	m_ListFilter.SetItemText(iItem,hfLocalAddress, m_sFilter.strLocalAddress);

	strWork.Format(TEXT("%d"), m_sFilter.ulLocalPort);
	m_ListFilter.SetItemText(iItem, hfLocalPort, strWork);

	m_ListFilter.SetItemText(iItem, hfRemoteAddress, m_sFilter.strRemoteAddress);

	strWork.Format(TEXT("%d"), m_sFilter.ulRemotePort);
	m_ListFilter.SetItemText(iItem, hfRemotePort, strWork);
	
	item.iSubItem = hfState;
	item.pszText = "RESET";	
	item.iImage = static_cast<int>(icoInactive);
	m_ListFilter.SetItem(&item);

	m_ListFilter.Update(iItem);

	return true;
}
/////////////////////////////////////////////////////////////////////////////////
//
void CENetStatXDlg::OnMPopAddFilter() 
{
	AddFilter2List();
}
/////////////////////////////////////////////////////////////////////////////////
//
void CENetStatXDlg::OnDblclkLISTFilter(NMHDR* pNMHDR, LRESULT* pResult) 
{
	//get selected element
	LPNMITEMACTIVATE temp = (LPNMITEMACTIVATE) pNMHDR;
    m_nItem = temp->iItem;			//get the row number
    m_nSubItem = temp->iSubItem;	//get the column number
    if(m_nSubItem <= 0 || m_nItem == -1)
        return ;

    //Retrieve the text of the selected subItem from the list
	HWND hWnd1 =  ::GetDlgItem (m_hWnd, IDC_LIST_Filter);
    CString str = GetItemText(hWnd1, m_nItem, m_nSubItem);
	CString strProto(L"");

	LVITEM item;
	item.mask = LVIF_TEXT | LVIF_IMAGE;
	item.iItem = m_nItem;
	item.iSubItem = m_nSubItem;

	switch (m_nSubItem)
	{
		case hfProto:
			if(str == "TCP")
			{
				m_ListFilter.SetItemText(m_nItem, m_nSubItem, "UDP");
			}
			else if (str == "UDP")
			{
				m_ListFilter.SetItemText(m_nItem, m_nSubItem, "ICMP");
			}
			else if (str == "ICMP")
			{
				m_ListFilter.SetItemText(m_nItem, m_nSubItem, "ANY");
			}
			else
			{
				m_ListFilter.SetItemText(m_nItem, m_nSubItem, "TCP");
			}

		return;

		case hfDir:
			if (str == "OUT")
			{
				item.pszText = "IN";
    			item.iImage = static_cast<int>(icoIn);
			}
			else
			{
				item.pszText = "OUT";
    			item.iImage = static_cast<int>(icoOut);
			}
			m_ListFilter.SetItem(&item);
		return;

		case hfAction:
		case hfState:
			//do nothing
		return;

		case hfLocalAddress:
			if (str == "0.0.0.0")
				str = "127.0.0.1";
		break;
		
		case hfLocalPort: 
			str = "0";
		break;

		default:
			//draw edit box
		break;
	}

	RECT rect_subitem	= {0,0,0,0};
	RECT rect_list		= {0,0,0,0};
	RECT rect_dialog	= {0,0,0,0};
	// this macro is used to retrieve the Rectanle of the selected SubItem
	ListView_GetSubItemRect(hWnd1, temp->iItem, temp->iSubItem, LVIR_BOUNDS, &rect_subitem);

	//Get the Rectange of the listControl
	::GetWindowRect(temp->hdr.hwndFrom, &rect_list);
	ScreenToClient(&rect_list);

	//Get the Rectange of the Dialog
	::GetWindowRect(m_hWnd, &rect_dialog);
	ScreenToClient(&rect_dialog);

	if(m_nItem != -1)	
	{
		INT iLeft  = rect_subitem.left	+ (rect_list.left - rect_dialog.left);
		INT iTop   = rect_subitem.top	+ (rect_list.top  - rect_dialog.top) - 38; //rect_subitem.top + (y - (rect_subitem.bottom - rect_subitem.top) - 6),
		INT iWith  = rect_subitem.right - rect_subitem.left - 8;
		INT iHeigh = rect_subitem.bottom - rect_subitem.top - 4;

		::SetWindowPos(::GetDlgItem(m_hWnd,IDC_EDIT1), HWND_TOP, iLeft, iTop, iWith, iHeigh, NULL);

		//Set the listItem text in the EditBox
		::SetWindowText(::GetDlgItem(m_hWnd,IDC_EDIT1),str);
		::ShowWindow(::GetDlgItem(m_hWnd,IDC_EDIT1),SW_SHOW);
		::SetFocus(::GetDlgItem(m_hWnd,IDC_EDIT1));

		//Draw a Rectangle around the SubItem
		::Rectangle(::GetDC(temp->hdr.hwndFrom), rect_subitem.left, rect_subitem.top, rect_subitem.right, rect_subitem.bottom);
	}

	*pResult = 0;
}
/////////////////////////////////////////////////////////////////////////////////
//
//this function will returns the item text depending on the item and SubItem Index
CString CENetStatXDlg::GetItemText(HWND hWnd, int nItem, int nSubItem) const
{
	LVITEM lvi;
	memset(&lvi, 0, sizeof(LVITEM));
	lvi.iSubItem = nSubItem;
	CString str;
	int nLen = 128;
	int nRes;
	do
	{
		nLen *= 2;
		lvi.cchTextMax = nLen;
		lvi.pszText = str.GetBufferSetLength(nLen);
		nRes  = (int)::SendMessage(hWnd, LVM_GETITEMTEXT, (WPARAM)nItem,(LPARAM)&lvi);
	} while (nRes == nLen-1);
	str.ReleaseBuffer();
	return str;
}
/////////////////////////////////////////////////////////////////////////////////
//
// This function set the text in the specified SubItem depending on the Row and Column values
void CENetStatXDlg::SetCell(HWND hWnd1, CString value, int nRow, int nCol)
{
	TCHAR     szString [256];
	wsprintf(szString,value ,0);

	//Fill the LVITEM structure with the values given as parameters.
	LVITEM lvItem;
	lvItem.mask = LVIF_TEXT;
	lvItem.iItem = nRow;
	lvItem.pszText = szString;
	lvItem.iSubItem = nCol;
	if(nCol >0)
	//set the value of listItem
	::SendMessage(hWnd1,LVM_SETITEM, (WPARAM)0,(WPARAM)&lvItem);
	else
	//Insert the value into List
	ListView_InsertItem(hWnd1,&lvItem);

}
/////////////////////////////////////////////////////////////////////////////////
//
// This function handles the ENTER key 
void CENetStatXDlg::OnOK() 
{	
    CWnd* pwndCtrl = GetFocus();
    // get the control ID which is presently having the focus
	int ctrl_ID = pwndCtrl->GetDlgCtrlID();
	CString str;
    switch (ctrl_ID)
	{	//if the control is the EditBox	
        case IDC_EDIT1:
			//get the text from the EditBox
			GetDlgItemText(IDC_EDIT1,str);
			//set the value in the listContorl with the specified Item & SubItem values
			SetCell(::GetDlgItem (m_hWnd,IDC_LIST_Filter),str,m_nItem,m_nSubItem);
			::SendDlgItemMessage(m_hWnd,IDC_EDIT1,WM_KILLFOCUS,0,0);
			::ShowWindow(::GetDlgItem(m_hWnd,IDC_EDIT1),SW_HIDE);
        break;     
        default:
        break;
    }
}
/////////////////////////////////////////////////////////////////////////////////
//
void CENetStatXDlg::OnDblclkLISTMain(NMHDR* pNMHDR, LRESULT* pResult) 
{
	//reset error filter
	m_bFilterError = FALSE;

	//gather info about selected line
	int nItem = -1;
	POSITION pos = m_ListMain.GetFirstSelectedItemPosition();

	if (pos == NULL) TRACE("No items were selected!\n");
	else
	{
	   while (pos)
	   {
		  nItem = m_ListMain.GetNextSelectedItem(pos);
		  TRACE1("Item %d was selected!\n", nItem);
	   }
	}

	//insert filter data in the filter list
	if (nItem != -1)
	{
		//read selected data		
		CString strWork(L"");		
		INTERFACE_HANDLE hInt = NULL;		

		strWork = m_ListMain.GetItemText(nItem,0);		
		if(strWork == _TEXT("TCP")) 		
		{		
			m_sFilter.dwProto = IPPROTO_TCP;		
			m_sFilter.eAction = PF_ACTION_FORWARD;
			m_sFilter.eInOut = in;
			m_sFilter.strLocalAddress = m_ListMain.GetItemText(nItem, 3);		
			m_sFilter.ulLocalPort = atoi(m_ListMain.GetItemText(nItem, 4));		
			m_sFilter.strRemoteAddress = m_ListMain.GetItemText(nItem,5);		
			m_sFilter.ulRemotePort = atoi(m_ListMain.GetItemText(nItem,6));		
		}		
		else 		
		{		
			m_sFilter.dwProto = IPPROTO_UDP;
			m_sFilter.eAction = PF_ACTION_FORWARD;
			m_sFilter.eInOut = in;			
			m_sFilter.strLocalAddress = m_ListMain.GetItemText(nItem, 3);		
			m_sFilter.ulLocalPort = atoi(m_ListMain.GetItemText(nItem, 4));		
			m_sFilter.strRemoteAddress = "0.0.0.0";		
			m_sFilter.ulRemotePort = FILTER_TCPUDP_PORT_ANY;		
		}
	}

	if (false == AddFilter2List())
		m_bar.SetPaneText(0,"Error adding to filter list ...");				

	*pResult = 0;
}
/////////////////////////////////////////////////////////////////////////////////
//
void CENetStatXDlg::CheckMenu(UINT idSubItem)
{
	   CMenu* mmenu = GetMenu();
	   CMenu* submenu = mmenu->GetSubMenu(0);

	   UINT state = submenu->GetMenuState(idSubItem, MF_BYCOMMAND);
	   ASSERT(state != 0xFFFFFFFF);
/*
	   if (state & MF_CHECKED)
		  submenu->CheckMenuItem(idSubItem, MF_UNCHECKED | MF_BYCOMMAND);
	   else
		  submenu->CheckMenuItem(idSubItem, MF_CHECKED | MF_BYCOMMAND);
*/
	   submenu->CheckMenuRadioItem(ID_FILE_REFRESH_1S, ID_FILE_REFRESH_60S, idSubItem, MF_BYCOMMAND);
}
/////////////////////////////////////////////////////////////////////////////////
//
void CENetStatXDlg::OnFileRefresh1s() 
{
	UpdateData();
	
	SuspendThread(m_hndThUser); //suspend thread
	ms_dwUpdateTime	= 1 * 1000; //update cycle time 
	ResumeThread(m_hndThUser);	//resume thread

	InitListAll();
	CheckMenu(ID_FILE_REFRESH_1S);
}
/////////////////////////////////////////////////////////////////////////////////
//
void CENetStatXDlg::OnFileRefresh5s() 
{
	UpdateData();

	SuspendThread(m_hndThUser); //suspend thread
	ms_dwUpdateTime	= 5 * 1000; //update cycle time 
	ResumeThread(m_hndThUser);	//resume thread

	InitListAll();
	CheckMenu(ID_FILE_REFRESH_5S);
}
/////////////////////////////////////////////////////////////////////////////////
//
void CENetStatXDlg::OnFileRefresh10s() 
{
	UpdateData();

	SuspendThread(m_hndThUser); //suspend thread
	ms_dwUpdateTime	= 10 * 1000; //update cycle time 
	ResumeThread(m_hndThUser);	//resume thread

	InitListAll();
	CheckMenu(ID_FILE_REFRESH_10S);
}
/////////////////////////////////////////////////////////////////////////////////
//
void CENetStatXDlg::OnFileRefresh20s() 
{
	UpdateData();

	SuspendThread(m_hndThUser); //suspend thread
	ms_dwUpdateTime	= 20 * 1000; //update cycle time 
	ResumeThread(m_hndThUser);	//resume thread

	InitListAll();
	CheckMenu(ID_FILE_REFRESH_20S);
}
/////////////////////////////////////////////////////////////////////////////////
//
void CENetStatXDlg::OnFileRefresh60s() 
{
	UpdateData();

	SuspendThread(m_hndThUser); //suspend thread
	ms_dwUpdateTime	= 60 * 1000; //update cycle time 
	ResumeThread(m_hndThUser);	//resume thread

	InitListAll();
	CheckMenu(ID_FILE_REFRESH_60S);
}
/////////////////////////////////////////////////////////////////////////////////
//
void CENetStatXDlg::OnFileRefreshNowf5() 
{
	UpdateData();
	CheckMenu(ID_FILE_REFRESH_NOWF5);
	InitListAll();	
}
/////////////////////////////////////////////////////////////////////////////////
//
void CENetStatXDlg::OnSniffEnable() 
{
	//it is allowed only ones
	if (m_bFlagInit == FALSE)
		m_bFlagInit	= m_pSniff->Create(this->m_hWnd, WM_SOCKEVENT);		
}
/////////////////////////////////////////////////////////////////////////////////
//
void CENetStatXDlg::OnSniffDisable() 
{
	//it is allowed only ones
	if (m_bFlagInit == TRUE)
		m_bFlagInit	= m_pSniff->Clean(this->m_hWnd);
}
/////////////////////////////////////////////////////////////////////////////////
//
void CENetStatXDlg::OnMenuPopFilterSet() 
{
	char			 szBuff[80];				//used to format last error code
	CString			 strError (L"");
	INTERFACE_HANDLE hInt = NULL;	
					 
	m_bFilterError = FALSE;						//reset error filter

	//*****************************************************************
	//gather filter data

		//Proto
		CString strProto = m_ListFilter.GetItemText(m_nItemFilter, hfProto);
		if (strProto == _TEXT("TCP"))
		{
			m_sFilter.dwProto = FILTER_PROTO_TCP;
			m_sFilter.strLocalAddress = m_ListFilter.GetItemText(m_nItemFilter, hfLocalAddress);		
			m_sFilter.ulLocalPort = atoi(m_ListFilter.GetItemText(m_nItemFilter, hfLocalPort));		
			m_sFilter.strRemoteAddress = m_ListFilter.GetItemText(m_nItemFilter, hfRemoteAddress);
			m_sFilter.ulRemotePort = atoi(m_ListFilter.GetItemText(m_nItemFilter, hfRemotePort));
		}
		else if(strProto == _TEXT("UDP"))
		{
			m_sFilter.dwProto = FILTER_PROTO_UDP;
			m_sFilter.strLocalAddress = m_ListFilter.GetItemText(m_nItemFilter, hfLocalAddress);		
			m_sFilter.ulLocalPort = atoi(m_ListFilter.GetItemText(m_nItemFilter, hfLocalPort));		
			m_sFilter.strRemoteAddress = m_ListFilter.GetItemText(m_nItemFilter, hfRemoteAddress);
			m_sFilter.ulRemotePort = FILTER_TCPUDP_PORT_ANY;
		}
		else if(strProto == _TEXT("ICMP"))
		{
			m_sFilter.dwProto = FILTER_PROTO_ICMP;
			m_sFilter.strLocalAddress = m_ListFilter.GetItemText(m_nItemFilter, hfLocalAddress);		
			m_sFilter.ulLocalPort = FILTER_TCPUDP_PORT_ANY;
			m_sFilter.strRemoteAddress = m_ListFilter.GetItemText(m_nItemFilter, hfRemoteAddress);		
			m_sFilter.ulRemotePort = FILTER_TCPUDP_PORT_ANY;
		}
		else
		{
			m_sFilter.dwProto = FILTER_PROTO_ANY;
			m_sFilter.strLocalAddress = m_ListFilter.GetItemText(m_nItemFilter, hfLocalAddress);		
			m_sFilter.ulLocalPort = atoi(m_ListFilter.GetItemText(m_nItemFilter, hfLocalPort));		
			m_sFilter.strRemoteAddress = m_ListFilter.GetItemText(m_nItemFilter, hfRemoteAddress);
			m_sFilter.ulRemotePort = atoi(m_ListFilter.GetItemText(m_nItemFilter, hfRemotePort));
		}

		//Action
		CString strAction = m_ListFilter.GetItemText(m_nItemFilter, hfAction);
		m_sFilter.eAction = PF_ACTION_FORWARD;
		/*if (strAction == _TEXT("Pass"))
			m_sFilter.eAction = PF_ACTION_FORWARD;
		else 
			m_sFilter.eAction = PF_ACTION_DROP;*/

		//Dir
		CString strDir = m_ListFilter.GetItemText(m_nItemFilter, hfDir);
		if (strDir == _TEXT("IN"))
			m_sFilter.eInOut = in;
		else 
			m_sFilter.eInOut = out;
	
	//*****************************************************************
	//SET filter
		hInt = m_pFilter->AddFilterEx(m_sFilter, false);		
		if (hInt != NULL)		
		{	
			m_bFilterError = FALSE;
			m_MapHInterf.SetAt(m_nItemFilter, hInt);	//used to delete particular filter
			m_ListHInterf.AddTail(hInt);				//used to release all filter interfaces
			m_bar.SetPaneText(0,"Success applying filter ...");

			//save the state
			LVITEM item;
			item.mask = LVIF_TEXT | LVIF_IMAGE;
			item.iItem = m_nItemFilter;
			item.iSubItem = hfState;
			item.pszText = "SET";	
			item.iImage = static_cast<int>(icoActive);
			m_ListFilter.SetItem(&item);
			//m_ListFilter.SetItemText(m_nItemFilter, hfState, "SET");
		}		
		else 
		{	
			m_bFilterError = TRUE;
			memset(szBuff, 0x00, sizeof(szBuff));
			FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,NULL,m_pFilter->ms_dwLastErrorCode,0,szBuff,sizeof(szBuff),NULL);
			strError = szBuff;
			m_bar.SetPaneText(0,"Error applying filter: " + strError);	
			
			//save the state
			m_ListFilter.SetItemText(m_nItemFilter, hfState, "SET error");
		}	
}
/////////////////////////////////////////////////////////////////////////////////
//
void CENetStatXDlg::OnFilterFilterDelete() 
{
	OnFilterFilterReset();
	m_ListFilter.DeleteItem(m_nItemFilter);
}
/////////////////////////////////////////////////////////////////////////////////
//
void CENetStatXDlg::OnFilterFilterReset() 
{
	char			 szBuff[80];				//used to format last error code
	CString			 strError (L"");
	INTERFACE_HANDLE hInt = NULL;	
					 
	m_bFilterError = FALSE;						//reset error filter

	//delete filter
		//identify hInterface from the list filter
		if (0 == m_MapHInterf.Lookup(m_nItemFilter, hInt))
		{
			m_bar.SetPaneText(0, "Error, retreiving interface handle from cache ...");
			return;
		}

		if (false == m_pFilter->RemoveFilter(hInt))
		{
			FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,NULL,m_pFilter->ms_dwLastErrorCode,0,szBuff,sizeof(szBuff),NULL);
			strError = szBuff;
			m_bar.SetPaneText(0,"Error reseting filter... operation still pending" + strError);	
			return;
		}
		else
		{
			//delete filter from cache
			m_MapHInterf.RemoveKey(m_nItemFilter);

			//save the state
			LVITEM item;
			item.mask = LVIF_TEXT | LVIF_IMAGE;
			item.iItem = m_nItemFilter;
			item.iSubItem = hfState;
			item.pszText = "RESET";	
			item.iImage = static_cast<int>(icoInactive);
			m_ListFilter.SetItem(&item);
			//m_ListFilter.SetItemText(m_nItemFilter, hfState, "RESET");
			m_bar.SetPaneText(0,"Success reseting filter ...");	
		}
}
/////////////////////////////////////////////////////////////////////////////////
//
void CENetStatXDlg::OnFilterFilterModify() 
{
	char			 szBuff[80];				//used to format last error code
	CString			 strError (L"");
	INTERFACE_HANDLE hInt = NULL;	
					 
	m_bFilterError = FALSE;						//reset error filter
	
		//identify hInterface from the list filter
		if (0 == m_MapHInterf.Lookup(m_nItemFilter, hInt))
		{
			m_bar.SetPaneText(0, "Error, retreiving interface handle from cache in order to modify it...");
			return;
		}
		
		//filter created before => modify filter
		if (FALSE == m_pFilter->RemoveFilter(hInt))
		{
			FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,NULL,m_pFilter->ms_dwLastErrorCode,0,szBuff,sizeof(szBuff),NULL);
			strError = szBuff;
			m_bar.SetPaneText(0, "Error reseting filter in order to modify it. " + strError);
			return;
		}
		//apply modified filter		
		hInt = m_pFilter->AddFilterEx(m_sFilter, false);		
		if (hInt != NULL)		
		{	
			m_bFilterError = FALSE;
			m_MapHInterf.SetAt(m_nItemFilter, hInt);		//used to delete particular filter
			m_ListHInterf.AddTail(hInt);					//used to release all filter interfaces
			m_bar.SetPaneText(0, "Success modifying filter ...");
			return;
		}		
		else 
		{	
			m_bFilterError = TRUE;
			memset(szBuff, 0x00, sizeof(szBuff));
			FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,NULL,m_pFilter->ms_dwLastErrorCode,0,szBuff,sizeof(szBuff),NULL);
			strError = szBuff;
			m_bar.SetPaneText(0, "Error modifying filter: " + strError);	
			return;
		}
}
/////////////////////////////////////////////////////////////////////////////////
//
void CENetStatXDlg::OnRclickLISTFilter(NMHDR* pNMHDR, LRESULT* pResult) 
{
	//*****************************************************************
	//Get selected Item
	int nItem = -1;
	POSITION pos = m_ListFilter.GetFirstSelectedItemPosition();
	if (pos == NULL) TRACE("No items were selected!\n");
	else
	{
	   while (pos)
	   {
		  nItem = m_ListFilter.GetNextSelectedItem(pos);
		  TRACE1("Item %d was selected!\n", nItem);
	   }
	}

	if(nItem == -1) //if not selected 
	{
		m_bar.SetPaneText(0, "Please select the item first and then check/uncheck the filter ...");
		return;
	}
	else 
	{
		m_nItemFilter = nItem;
	}

	//*****************************************************************
	//Load Pop-Up Menu
	POINT point = {0,0};
	::GetCursorPos(&point);

	CMenu menu;
	VERIFY(menu.LoadMenu(IDR_MENU_POP_FILTER));

	CMenu* pPopup = menu.GetSubMenu(0);
	ASSERT(pPopup != NULL);

	//*****************************************************************
	//Analize Pop-Up Menu
	/*Note: 
		IDR_MENU_POP_FILTER_SET
		ID_FILTER_FILTER_RESET
		ID_FILTER_FILTER_MODIFY
		ID_FILTER_FILTER_DELETE	
	*/
		CString strWork (L"");
		INTERFACE_HANDLE hInt = NULL;

		//filter not created before
		if (0 == m_MapHInterf.Lookup(m_nItemFilter, hInt))
		{
			//SET & DELETE available 
			pPopup->EnableMenuItem(ID_FILTER_FILTER_RESET, MF_GRAYED);
			pPopup->EnableMenuItem(ID_FILTER_FILTER_MODIFY, MF_GRAYED);
			pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y, this);
		}
		//filter created before
		else
		{
			//get the actual state
			strWork = m_ListFilter.GetItemText(m_nItemFilter, hfState);
			if (strWork == "SET")
			{
				//RESET & MODIFY & DELETE available 
				pPopup->EnableMenuItem(IDR_MENU_POP_FILTER_SET, MF_GRAYED);
				pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y, this);
			}
			else if (strWork == "RESET")
			{
				//SET & MODIFY & DELETE available 
				pPopup->EnableMenuItem(ID_FILTER_FILTER_RESET, MF_GRAYED);
				pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y, this);
			}
		}

	*pResult = 0; //don't touch it
}
/////////////////////////////////////////////////////////////////////////////////
//
void CENetStatXDlg::OnFilterFilterViewlog() 
{
	INTERFACE_HANDLE	hInt	= NULL;
	DWORD				dwSize	= 0;
	bool				bRez	= false;
	BYTE				*pBuff	= NULL; //PF_INTERFACE_STATS

	//identify hInterface from the list filter
	if (0 == m_MapHInterf.Lookup(m_nItemFilter, hInt))
	{
		m_bar.SetPaneText(0, "Error, retreiving interface handle from cache in order to view log...");
		return;
	}

	//bRez = m_pFilter->GetStatisticEx(hInt, pBuff, &dwSize); //dynamic
	bRez = m_pFilter->GetStatistic(hInt, &dwSize);		//static
	if (bRez == true) 
	{
		TRACE("\nsucceeded");
	}
	else
	{
		TRACE("\nfailed");
	}
}
/////////////////////////////////////////////////////////////////////////////////
//
void CENetStatXDlg::OnKeydownLISTMain(NMHDR* pNMHDR, LRESULT* pResult) 
{
	LV_KEYDOWN* pLVKeyDow = (LV_KEYDOWN*)pNMHDR;
	switch(pLVKeyDow->wVKey)
	{
		case VK_F5:
			OnFileRefreshNowf5();
		break;
		
		default:
		break;
	}
		
	*pResult = 0;
}
/////////////////////////////////////////////////////////////////////////////////
//
void CENetStatXDlg::InitCriticalSection(void)
{
//logs
	//create thread for log
	CString strLogEvent(L"EnetstatLogEvent");

	//create event for log
	m_hndLogConnEvent = ::CreateEvent(NULL, FALSE, TRUE, strLogEvent);

	//create timer for tcp conn refresh
	//::SetTimer(m_hWnd, EVENT_TIMER_NEW_TCP_CONN, 500, NULL); //processed by WM_TIMER
	
	//::SetTimer(m_hWnd, EVENT_TIMER_NEW_TCP_CONN, 1000, (TIMERPROC)TcpNewConn_TimerProc);

//autoupdate 
	m_hndTh = ::CreateThread(NULL, 0, LogConn_ThreadProc, this->m_hWnd, THREAD_SUSPEND_RESUME, NULL);

//user update 
	m_hndThUser = ::CreateThread(NULL, 0, LogConn_ThreadProcUser, this->m_hWnd, THREAD_SUSPEND_RESUME, NULL);	
}
/////////////////////////////////////////////////////////////////////////////////
//
void CENetStatXDlg::OnFiltersniffEnable() 
{
	m_pFilter->SetLogFile("",m_hndLogConnEvent);
}
/////////////////////////////////////////////////////////////////////////////////
//
LRESULT CENetStatXDlg::OnLogMsg(WPARAM wParam, LPARAM lParam)
{
	TRACE("\nCENetStatXDlg::OnLogMsg()");

	//get logframe
	DWORD dwLoggEn = m_pFilter->m_sLogParam.pdwLoggedEntries;
	DWORD dwLostEn = m_pFilter->m_sLogParam.pdwLostEntries;
	DWORD dwSzUsed = m_pFilter->m_sLogParam.pdwSizeUsed;
			
	TRACE1("\n Logged Entries: %d", dwLoggEn);
	TRACE1("\n Lost Entries: %d", dwLostEn);
	TRACE1("\n Size Used: %d", dwSzUsed);

	//(PFLOGFRAME)m_pFilter->m_buffLog

	//cycle procedure
	if (false == m_pFilter->CycleLogFile())
		TRACE("\nError: m_pFilter->CycleLogFile()");

	return wParam;
}
/////////////////////////////////////////////////////////////////////////////////
//
void CENetStatXDlg::OnFileRefreshStop() 
{
	//stop autorefresh list
	UpdateData();
	::KillTimer(this->m_hWnd, EVENT_TIMER);		
}
/////////////////////////////////////////////////////////////////////////////////
//
void CENetStatXDlg::OnConnectionsViewAll() 
{
	m_eConnView	= viewAll;

	UpdateData();
	InitListAll();
}
/////////////////////////////////////////////////////////////////////////////////
//
void CENetStatXDlg::OnConnectionsViewConnected() 
{
	m_eConnView	= viewConnected;
	
	UpdateData();
	InitListAll();
}
/////////////////////////////////////////////////////////////////////////////////
//
LRESULT CENetStatXDlg::OnTrayNotification(WPARAM wParam, LPARAM lParam)
{
	// Delegate all the work back to the default implementation in CSystemTray.
	return m_TrayIcon.OnTrayNotification(wParam, lParam);	
}
/////////////////////////////////////////////////////////////////////////////////
//
void CENetStatXDlg::OnTrayExit() 
{
	SuspendThread(m_hndTh);
	SuspendThread(m_hndThUser);
	
	BOOL bRez = FALSE;
	DWORD dwExitCode = 0;
	bRez = GetExitCodeThread(m_hndTh, &dwExitCode);
	bRez = TerminateThread(m_hndTh, dwExitCode);
	bRez = GetExitCodeThread(m_hndThUser, &dwExitCode);
	bRez = TerminateThread(m_hndThUser, dwExitCode);
	
	m_TrayIcon.RemoveIcon();
	SendMessage(WM_CLOSE);
}
/////////////////////////////////////////////////////////////////////////////////
//
void CENetStatXDlg::OnTrayRestore() 
{
	m_bFocus = true;
	ShowWindow(SW_SHOW);
	SendMessage(SC_RESTORE);
	m_TrayIcon.HideIcon();
}
/////////////////////////////////////////////////////////////////////////////////
//
void CENetStatXDlg::OnRclickLISTMain(NMHDR* pNMHDR, LRESULT* pResult) 
{
	//*****************************************************************
	//Get selected Item
	int nItem = -1;
	POSITION pos = m_ListMain.GetFirstSelectedItemPosition();
	if (pos == NULL) TRACE("No items were selected!\n");
	else
	{
	   while (pos)
	   {
		  nItem = m_ListMain.GetNextSelectedItem(pos);
		  TRACE1("Item %d was selected!\n", nItem);
	   }
	}

	if(nItem == -1) //if not selected 
	{
		m_bar.SetPaneText(0, "Please select the item first and then choose the operation ...");
		return;
	}
	else 
	{
		m_nItemMain = nItem;
	}

	//*****************************************************************
	//Load Pop-Up Menu
	POINT point = {0,0};
	::GetCursorPos(&point);

	CMenu menu;
	VERIFY(menu.LoadMenu(IDR_MENU_SYSCONN));

	CMenu* pPopup = menu.GetSubMenu(0);
	ASSERT(pPopup != NULL);

	pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y, this);

	*pResult = 0; //don't touch it

}
/////////////////////////////////////////////////////////////////////////////////
//
void CENetStatXDlg::OnSysKillprocess() 
{
	CString strPid = m_ListMain.GetItemText(m_nItemMain, hPid);

	//query exit code
	HANDLE hndProc = ::OpenProcess(
			PROCESS_QUERY_INFORMATION,
			FALSE,
			static_cast<DWORD>(atoi(strPid)));
	if(hndProc == NULL)
	{
		m_bar.SetPaneText(0,"Error openning process in order to kill it ...");
		return;
	}

	DWORD dwExitCode = 0;
	if (FALSE == GetExitCodeProcess(hndProc, &dwExitCode))
	{
		m_bar.SetPaneText(0,"Error getting exit code in order to kill it ...");
		return;
	}

	//terminate process
	hndProc = ::OpenProcess(
			PROCESS_TERMINATE,
			FALSE,
			static_cast<DWORD>(atoi(strPid)));
	if(hndProc == NULL)
	{
		m_bar.SetPaneText(0,"Error opening process in order to kill it ...");
		return;
	}

	if (FALSE == TerminateProcess(hndProc, dwExitCode))
	{
		m_bar.SetPaneText(0,"Error terminating process ...");
		return;
	}
	
	CloseHandle(hndProc);
	InitListAll();
}
/////////////////////////////////////////////////////////////////////////////////
//
int CENetStatXDlg::GetProcessIcon(CString strAppName, CString strPathAppName)
{
	/*
	 *	Note: -> there is no need to clean-up the map: knowledge is better
	 *        -> icon cache mechanism 
	 */
	int nUnk = 1;		//default icon (app without icon)
	int nIcoIndex = -1; 

	if (strPathAppName.IsEmpty() || (strPathAppName == "error"))
		return nUnk; //default for unk process

	if (strAppName.IsEmpty())
		strAppName = strPathAppName.Right((strPathAppName.GetLength()-1) - strPathAppName.ReverseFind('\\'));

	//is it already assigned ?
	Ico2Index::iterator it = m_mProcName2IcoIndex.find(strAppName);
	if (it != m_mProcName2IcoIndex.end())
	{
		TRACE2("\n Existing map, process: %s, icon: %d\n",(*it).first, m_mProcName2IcoIndex[strAppName]);
		nIcoIndex = m_mProcName2IcoIndex[strAppName];
		return --nIcoIndex;
	}
	
	//add a new record
	HICON hSmallIco = NULL;
	if (NULL == (hSmallIco = ::ExtractIcon(NULL, strPathAppName, 0)))
		return nUnk;
	 
	m_pImageListMain->Add(hSmallIco);
	DestroyIcon(hSmallIco);

	nIcoIndex = (m_pImageListMain->GetImageCount());
	if (nIcoIndex >= 1)
	{
		TRACE2("\n New map, process: %s, icon: %d\n", strAppName, nIcoIndex);
		m_mProcName2IcoIndex[strAppName] = nIcoIndex;
		return --nIcoIndex;
	}
	else
		return nUnk;
}
/////////////////////////////////////////////////////////////////////////////////
//
void CENetStatXDlg::OnSysCloseConnection() 
{
	MIB_TCPROW sKillConn;

	sKillConn.dwState	   = MIB_TCP_STATE_DELETE_TCB;
	sKillConn.dwLocalAddr  = (DWORD)inet_addr((LPCSTR)m_ListMain.GetItemText(m_nItemMain, hLocalAddress));
	sKillConn.dwRemoteAddr = (DWORD)inet_addr((LPCSTR)m_ListMain.GetItemText(m_nItemMain, hRemoteAddress));
	
	CString strLP		   = m_ListMain.GetItemText(m_nItemMain, hLocalPort);
	sKillConn.dwLocalPort  = (DWORD)htons((u_short)atoi(strLP.GetBuffer(strLP.GetLength())));
	//sKillConn.dwLocalPort  = strtod((LPCSTR)strLP, (LPSTR*)&strLP);

	CString strRP		   = m_ListMain.GetItemText(m_nItemMain, hRemotePort);
	sKillConn.dwRemotePort = (DWORD)htons((u_short)atoi(strRP.GetBuffer(strRP.GetLength())));
	//sKillConn.dwRemotePort = strtod((LPCSTR)strRP, (LPSTR*)&strRP);
	
	DWORD dwRez = SetTcpEntry(&sKillConn);
	if(dwRez != NO_ERROR)
	{
		dwRez = ::GetLastError();
		m_bar.SetPaneText(0,"Error closing connection ;(");
		TRACE("\nError closing connection ;(\n");
		return;
	}
	
	InitListAll();
	m_bar.SetPaneText(0,"Success closing connection ;)");
	TRACE("\nSuccess closing connection ;(\n");
}
/////////////////////////////////////////////////////////////////////////////////
//
void CENetStatXDlg::OnSize(UINT nType, int cx, int cy) 
{
	CDialog::OnSize(nType, cx, cy);
	
	RepositionBars(AFX_IDW_CONTROLBAR_FIRST,AFX_IDW_CONTROLBAR_LAST,ID_INDICATOR_TIME);

	CRect rcSplitter	(0,0,0,0);
	CRect rcDialog		(0,0,0,0);
	CWnd* pWndSplitter	= GetDlgItem(ID_FAKE_CONTROL);
	CWnd* pWndDialog	= GetDlgItem(IDC_LIST_Main);

	if ((NULL != pWndSplitter) && (NULL != pWndDialog))
	{
		pWndSplitter->GetWindowRect(rcSplitter);
		pWndDialog->GetWindowRect(rcDialog);

		ScreenToClient(rcSplitter);
		ScreenToClient(rcDialog);
		rcSplitter.right = rcDialog.right;
		
		m_ctrlSplitterBar.SetSplitterRect(&rcSplitter);

		//::SetWindowPos(pWndSplitter->m_hWnd, HWND_TOP, &rcSplitter ,SWP_SHOWWINDOW);
		
		::ShowWindow(::GetDlgItem(m_hWnd,ID_FAKE_CONTROL),SW_SHOW);
		::SetFocus(::GetDlgItem(m_hWnd,ID_FAKE_CONTROL));
	}

	UPDATE_EASYSIZE;	
}
/////////////////////////////////////////////////////////////////////////////////
//
void CENetStatXDlg::OnSizing(UINT fwSide, LPRECT pRect) 
{
	CDialog::OnSizing(fwSide, pRect);

	RepositionBars(AFX_IDW_CONTROLBAR_FIRST,AFX_IDW_CONTROLBAR_LAST,ID_INDICATOR_TIME);

	CRect rcSplitter	(0,0,0,0);
	CRect rcDialog		(0,0,0,0);
	CWnd* pWndSplitter	= GetDlgItem(ID_FAKE_CONTROL);
	CWnd* pWndDialog	= GetDlgItem(IDC_LIST_Main);

	if ((NULL != pWndSplitter) && (NULL != pWndDialog))
	{
		pWndSplitter->GetWindowRect(rcSplitter);
		pWndDialog->GetWindowRect(rcDialog);

		ScreenToClient(rcSplitter);
		ScreenToClient(rcDialog);
		rcSplitter.right = rcDialog.right;
		
		m_ctrlSplitterBar.SetSplitterRect(&rcSplitter);

		//::SetWindowPos(pWndSplitter->m_hWnd, HWND_TOP, &rcSplitter ,SWP_SHOWWINDOW);
		
		::ShowWindow(::GetDlgItem(m_hWnd,ID_FAKE_CONTROL),SW_SHOW);
		::SetFocus(::GetDlgItem(m_hWnd,ID_FAKE_CONTROL));
	}
		
	EASYSIZE_MINSIZE(0,0,fwSide, pRect);	
}
/////////////////////////////////////////////////////////////////////////////////
//
//DEL LRESULT CENetStatXDlg::DefWindowProc(UINT message, WPARAM wParam, LPARAM lParam) 
//DEL {
//DEL 	if (message == WM_NOTIFY)
//DEL 	{
//DEL 		if (wParam == IDC_STATIC_SPLITTER)
//DEL 		{	
//DEL 			SPC_NMHDR* pHdr = (SPC_NMHDR*) lParam;
//DEL 			DoResizeSplitter(pHdr->delta);
//DEL 		}
//DEL 	}
//DEL 	
//DEL 	return CDialog::DefWindowProc(message, wParam, lParam);
//DEL }
/////////////////////////////////////////////////////////////////////////////////
//
//DEL void CENetStatXDlg::DoResizeSplitter(int delta)
//DEL {
//DEL 	CSplitterControl::ChangeHeight(&m_ListMain, delta);
//DEL 	CSplitterControl::ChangeHeight(&m_ListFilter, -delta, CW_BOTTOMALIGN);
//DEL 	Invalidate();
//DEL 	UpdateWindow();
//DEL }
/////////////////////////////////////////////////////////////////////////////////
//
//DEL void CENetStatXDlg::DoResizeSplitter(void)
//DEL {
//DEL 	CRect rc;
//DEL 	CWnd* pWnd;
//DEL 	pWnd = GetDlgItem(IDC_STATIC_SPLITTER);
//DEL 	pWnd->GetWindowRect(rc);
//DEL 	ScreenToClient(rc);
//DEL 	m_wndSplitter.Create(WS_CHILD | WS_VISIBLE, rc, this, IDC_STATIC_SPLITTER);
//DEL 	m_wndSplitter.SetRange(50, 50, -1);
//DEL }
/////////////////////////////////////////////////////////////////////////////////
//

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
Romania Romania
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions