// AutoRun2Dlg.cpp : implementation file
//

#include "stdafx.h"
#include "AutoRun2.h"
#include "AutoRun2Dlg.h"
#include "AutoRun2Dlg2.h"
#include <afxsock.h>//<Winsock2.h>
#include "ConnectDlg.h"
#include "SendDataDlg.h"
#include "AddContact.h"
#include "SendReg.h"
#include <Mmsystem.h>
#include <tlhelp32.h>
#include <afxinet.h>
#include <afxext.h>
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#pragma comment(lib, "Winmm.lib")
#define IPC_CUSTOM_MSG2	_T("{a4Fa76E2-w78F-2aD5-q98A-Y0B0D078u2}")
UINT g_wmClose = RegisterWindowMessage(IPC_CUSTOM_MSG2);
CString g_mainpath;
CString g_mainpath2;
CString g_mainpath3;
BOOL g_bAutoRun=0;
#define WM_ICON_NOTIFY  WM_USER+12
DWORD g_nSendCode=0;    //insert
/////////////////////////////////////////////////////////////////////////////
DWORD g_ncount2=0;
HWND g_hSendWnd; 
extern HWND g_hConnectWnd;
extern void DataToArray(CArray<CStringArray, CStringArray>*List1array);
extern void DataToArray(CArray<CStringArray, CStringArray>*List1array, CArray<CStringArray, CStringArray>*List2array);
#define DISCONNECT_TIMER	(WM_USER + 101)
#define LOGINFAILED_TIMER	(WM_USER + 102)
extern void MyGetIPByName(CString &name);
BOOL g_bReturned=0;
BOOL g_bReturned2=0;

int GetCount(CString content)
{
	int count=0;
	int leng=g_pMainWnd->GetLengthEx(content);
	{
		count+=1*(leng/70);
		if(leng%70)
			count+=1;
	}

	return count;
}
DWORD FindAppProcessID(CString path)
{
	try
	{
		HANDLE handle=::CreateToolhelp32Snapshot(TH32CS_SNAPALL,0);
		PROCESSENTRY32 Info;
		Info.dwSize = sizeof(PROCESSENTRY32);
		path.MakeLower ();
		if(::Process32First(handle,&Info))
		{
			do
			{
				CString ss=Info.szExeFile;
				ss.MakeLower ();
				if(ss.Find (path)!=-1 || (!ss.CompareNoCase(path)) )
				{
					::CloseHandle(handle);
					return Info.th32ProcessID;
				}
			}
			while(::Process32Next(handle,&Info));	
			::CloseHandle(handle);
		}
		return -1;
	}
	catch(...)
	{
	}
}
void WriteLogin(CString str)
{
	try
	{
		DWORD ticks=::GetTickCount ();
		CString path=g_mainpath2+"\\autorun.txt";
		{
			CFile fp;
			if(fp.Open (path, CFile::modeRead))
			{
				if(fp.GetLength ()/(1024*1024)>1)
				{
					fp.Close ();
					::DeleteFile (path);
				}
				else
					fp.Close ();
			}
		}

		CStdioFile fp;
		if(::PathFileExists (path))
		{
			fp.Open (path, CFile::modeWrite);
			fp.SeekToEnd ();
		}
		else
			fp.Open (path, CFile::modeCreate|CFile::modeWrite);
		CString temp;
		temp.Format (" %dss ", ::GetTickCount ()-ticks);
		fp.WriteString (CTime::GetCurrentTime ().Format ("%Y-%m-%d %H:%M:%S")+temp+str+"\r\n" );
		fp.Close ();
	}
	catch(...)
	{
	}
}
void MyExitWindows()
{
	try
	{
		UINT   t=EWX_REBOOT|EWX_FORCE;   
		OSVERSIONINFO   osv;     //����һ������ϵͳ��Ϣ�Ľṹ��   
		osv.dwOSVersionInfoSize=sizeof   OSVERSIONINFO;   
		GetVersionEx(&osv);       //��ѯ��ǰ����ϵͳ   
		if(osv.dwPlatformId==VER_PLATFORM_WIN32_NT)     //�ж��Ƿ���2000/NT   
		{   
			//����Ϊ�����ϵͳ��ȡȨ�޲���   
			HANDLE   hProcess,hToken;   
			TOKEN_PRIVILEGES   Privileges;   
			LUID   luid;   
			hProcess=GetCurrentProcess();   
			//����Ϊ�򿪵�ǰ���̶Ի�   
			OpenProcessToken(hProcess,TOKEN_ADJUST_PRIVILEGES,&hToken);   
			Privileges.PrivilegeCount=1;   
			LookupPrivilegeValue(NULL,SE_SHUTDOWN_NAME,&luid);   
			Privileges.Privileges[0].Luid=luid;   
			Privileges.Privileges[0].Attributes=SE_PRIVILEGE_ENABLED;   
			AdjustTokenPrivileges(hToken,FALSE,&Privileges,NULL,NULL,NULL);   
			ExitWindowsEx(t,0);   
		}   
		else
		{
			ExitWindowsEx(t,0);//����ExitWindowsEx�رջ�����     
			PostQuitMessage(0);   
		}
	}
	catch(...)
	{
	}
}

/////////////////////////////////////////////////////////////////////////////
static void HandleClientNetEvent(IN SOCKET hSocket, IN ETransportEvent eEvent, 
								 IN void *pDataBuf, IN unsigned long nDataLen, 
								 IN int nError, IN void *pContext)
{
	if( nError != TRANSPORT_OK ) return;

	CAutoRun2Dlg *pDlg = (CAutoRun2Dlg *)pContext;
	if( NULL == pDlg ) return;
	pDlg->ProcessNetEvent(eEvent, pDataBuf, nDataLen);
}

CAutoRun2Dlg::CAutoRun2Dlg(CWnd* pParent /*=NULL*/)
: CDialog(CAutoRun2Dlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CAutoRun2Dlg)
	m_strSendSms = _T("");
	m_strLoginID = _T("");
	m_strLoginPwd = _T("");
	m_strRecvMobi = _T("");
	m_strNewPwd = _T("");
	m_mobicount = 0;
	m_check1 = FALSE;
	m_count = 0;
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
	m_nMobile=0;
	m_nPhone=0;
	CString version = _T ("Version 1.0");
	g_bAutoRun=AfxGetApp()->GetProfileInt (version, "brun", 0);


}

void CAutoRun2Dlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAutoRun2Dlg)
	DDX_Control(pDX, IDC_LIST2, m_List1);
	DDX_Control(pDX, IDC_BTN_SEND, m_btnSend);
	DDX_Control(pDX, IDC_LST_SMS, m_listCtrl);
	DDX_Text(pDX, IDC_EDT_SMS, m_strSendSms);
	DDV_MaxChars(pDX, m_strSendSms, 2000);
	DDX_Text(pDX, IDC_EDT_LOGIN_ID, m_strLoginID);
	DDV_MaxChars(pDX, m_strLoginID, 11);
	DDX_Text(pDX, IDC_EDT_LOGIN_PWD, m_strLoginPwd);
	DDX_Text(pDX, IDC_EDT_RECV_MOBI, m_strRecvMobi);
	DDX_Text(pDX, IDC_EDT_NEW_PWD, m_strNewPwd);
	DDX_Text(pDX, IDC_EDT_NUM, m_mobicount);
	DDX_Check(pDX, IDC_CHECK1, m_check1);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAutoRun2Dlg, CDialog)
	//{{AFX_MSG_MAP(CAutoRun2Dlg)
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_WM_DESTROY()
	ON_BN_CLICKED(IDC_BTN_SEND, OnBtnSend)
	ON_BN_CLICKED(IDC_BTN_QUERY, OnBtnQuery)
	ON_BN_CLICKED(IDC_BTN_Query2, OnBTNQuery2)
	ON_BN_CLICKED(IDC_BTN_CHANGE_PWD, OnBtnChangePwd)	
	ON_BN_CLICKED(IDC_BTN_GET_STATUS, OnBtnGetStatus)
	ON_WM_TIMER()
	ON_BN_CLICKED(IDC_BUTadd, OnBUTadd)
	ON_BN_CLICKED(IDC_BUTdel, OnBUTdel)
	ON_LBN_SELCHANGE(IDC_LIST2, OnSelchangeList2)
	ON_EN_CHANGE(IDC_EDT_SMS, OnChangeEdtSms)
	ON_EN_CHANGE(IDC_EDT_RECV_MOBI, OnChangeEdtRecvMobi)
	ON_BN_CLICKED(IDC_CHECK1, OnCheck1)
	ON_BN_CLICKED(IDC_BTN_REG, OnBtnReg)
	ON_COMMAND(IDM_CLOSE, OnClose)
	ON_COMMAND(IDM_AUTORUN, OnAutorun)
	//}}AFX_MSG_MAP
	ON_MESSAGE(WM_ICON_NOTIFY, OnTrayNotification)
	ON_REGISTERED_MESSAGE(g_wmClose, OnAbortClose)
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
LRESULT CAutoRun2Dlg::OnTrayNotification(WPARAM wParam,LPARAM lParam)
{
	return m_TrayIcon.OnTrayNotification(wParam,lParam);
}
LRESULT CAutoRun2Dlg::OnAbortClose(WPARAM wParam, LPARAM lParam)
{
	KillTimer(5);
	return 1;
}
BOOL CAutoRun2Dlg::OnInitDialog()
{
	SetWindowPos(&wndNoTopMost,0,0,0,0,SWP_HIDEWINDOW);   
	ModifyStyleEx(WS_EX_APPWINDOW,WS_EX_TOOLWINDOW); 
	CDialog::OnInitDialog();

	// 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
	g_pMainWnd=this;
	char path[MAX_PATH];
	::GetModuleFileName (NULL, path, MAX_PATH);
	g_mainpath=path;
	g_mainpath=g_mainpath.Left (g_mainpath.ReverseFind ('\\'));
	g_mainpath3=g_mainpath2=g_mainpath;

	g_mainpath+="\\LYFZMsgManage.exe";
	g_mainpath3+="\\LYFZIPManage.exe";

	ShellExecute(NULL, _T("open"), g_mainpath, "0", NULL,  SW_SHOWNORMAL); 
	ShellExecute(NULL, _T("open"), g_mainpath3, "0", NULL,  SW_SHOWNORMAL);

	ShellExecute(NULL, _T("open"), g_mainpath2+"\\AutoRun3.exe", "0", NULL,  SW_SHOWNORMAL); 

	ShellExecute(NULL, _T("open"), g_mainpath2+"\\LYFZReceiveMsg.exe", "0", NULL,  SW_SHOWNORMAL); 
	ShellExecute(NULL, _T("open"), g_mainpath2+"\\LYFZReceiveMsg.exe", "1", NULL,  SW_SHOWNORMAL); 
	ShellExecute(NULL, _T("open"), g_mainpath2+"\\LYFZReceiveMsg.exe", "2", NULL,  SW_SHOWNORMAL); 
	ShellExecute(NULL, _T("open"), g_mainpath2+"\\LYFZReceiveMsg.exe", "3", NULL,  SW_SHOWNORMAL); 
	ShellExecute(NULL, _T("open"), g_mainpath2+"\\LYFZReceiveMsg.exe", "4", NULL,  SW_SHOWNORMAL); 
	ShellExecute(NULL, _T("open"), g_mainpath2+"\\LYFZReceiveMsg.exe", "5", NULL,  SW_SHOWNORMAL); 
	ShellExecute(NULL, _T("open"), g_mainpath2+"\\LYFZReceiveMsg.exe", "6", NULL,  SW_SHOWNORMAL); 
	ShellExecute(NULL, _T("open"), g_mainpath2+"\\LYFZReceiveMsg.exe", "20", NULL,  SW_SHOWNORMAL); 

	ShellExecute(NULL, _T("open"), g_mainpath2+"\\LYFZSendMsg.exe", NULL, NULL,  SW_SHOWNORMAL); 

	ShellExecute(NULL, _T("open"), g_mainpath2+"\\LYFZIPReceive.exe", "0", NULL,  SW_SHOWNORMAL); 
	ShellExecute(NULL, _T("open"), g_mainpath2+"\\LYFZIPReceive.exe", "1", NULL,  SW_SHOWNORMAL); 
	ShellExecute(NULL, _T("open"), g_mainpath2+"\\LYFZIPReceive.exe", "2", NULL,  SW_SHOWNORMAL); 
	ShellExecute(NULL, _T("open"), g_mainpath2+"\\LYFZIPReceive.exe", "3", NULL,  SW_SHOWNORMAL); 
	ShellExecute(NULL, _T("open"), g_mainpath2+"\\LYFZIPReceive.exe", "4", NULL,  SW_SHOWNORMAL); 
	ShellExecute(NULL, _T("open"), g_mainpath2+"\\LYFZIPReceive.exe", "5", NULL,  SW_SHOWNORMAL); 
	ShellExecute(NULL, _T("open"), g_mainpath2+"\\LYFZIPReceive.exe", "6", NULL,  SW_SHOWNORMAL); 

	UpdateMyIP();

	SetTimer(5, 10*60*1000, NULL);
	//	SetTimer  (6, 60*60*1000, NULL);
	/////////////////////////////////
	// TODO: Add extra initialization here
	return TRUE;  // return TRUE  unless you set the focus to a control
}

// 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 CAutoRun2Dlg::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 CAutoRun2Dlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

DWORD CAutoRun2Dlg::GetConnectionID()
{
	return m_dwConnectionID;
}

void CAutoRun2Dlg::SetConnectionID(DWORD dwConnection)
{
	m_dwConnectionID = dwConnection;
}

void CAutoRun2Dlg::ProcessChatMessageRequest2(CString sql)
{
	const char *szDataBuf = sql.GetBuffer(0);
	sql.ReleaseBuffer();
	ProcessChatMessageRequest((void*)szDataBuf, strlen(szDataBuf) + 1);
}

void CAutoRun2Dlg::ProcessChatMessageRequest2(BYTE *pData, int length)
{
	ProcessChatMessageRequest((void*)pData, length);
}

BOOL CAutoRun2Dlg::ProcessChatMessageRequest(void *szDataBuf, int nDataLen)
{
	g_bReturned=0;
	DWORD dwFromUserID = GetConnectionID();
	WORD wMessageId = MSG_CHATMESSAGE_REQ;
	DWORD dwDataLen = sizeof(TCHAT_MESSAGE_STRU) + nDataLen;

	BYTE *pSendData = new BYTE[dwDataLen];
	TCHAT_MESSAGE_STRU *pChatMessage=(TCHAT_MESSAGE_STRU*)pSendData;
	memset(pChatMessage, 0x00, dwDataLen);
	g_sendhead.length[98]=987123768;


	memcpy(pSendData, &g_sendhead, sizeof(g_sendhead));


	pChatMessage->tCommonMsg.dwConnectionID = GetConnectionID();
	pChatMessage->tCommonMsg.wMessageId = wMessageId;
	pChatMessage->dwFromUserID = dwFromUserID;
	pChatMessage->dwToUserID = g_nSendCode;

	pChatMessage->wMessageLen = nDataLen;
	memcpy(pChatMessage->byFileContent, szDataBuf, nDataLen);

	TMessageHeader tHeader = {0};
	tHeader.wMessageId = wMessageId;
	tHeader.dwDataLen = dwDataLen;

	BOOL bRet=0;
	unsigned long ulSendLen = m_tClientTunnel.net_Send(&tHeader, (void *)pChatMessage, dwDataLen);
	if( ulSendLen != SOCKET_ERROR )
	{
		bRet=1;
	}
	delete [] pSendData;
	return bRet;
}

BOOL CAutoRun2Dlg::OnConnect()
{
	g_server="lijiafz.vicp.net" ;
	MyGetIPByName(g_server);
	if(g_server.IsEmpty ())return OnConnect2();
	CString strServerAddress = g_server;
	char *szServerAddress = strServerAddress.GetBuffer(0);
	strServerAddress.ReleaseBuffer();

	/*for Client, IP and Port can be 0, 
	and for Server, IP is LocalIP, and Port is Listening Port*/
	int nResult = m_tClientTunnel.net_OpenSocket(Transport_Client, 
		0,
		HandleClientNetEvent, 
		this);
	if( TRANSPORT_OK != nResult )
	{	
		return 0;
	}

	DWORD dwRemoteIPValue = inet_addr(szServerAddress);
	WORD wPort = SERVER_PORT;	
	nResult = m_tClientTunnel.net_Connect(dwRemoteIPValue, wPort);
	if( TRANSPORT_OK != nResult )
	{
		m_tClientTunnel.net_CloseSocket();
		return OnConnect2();
	}
	return ProcessLoginRequest();
}

BOOL CAutoRun2Dlg::OnConnect2()
{
	CString server="http://www.lyfz.net/download/ip.txt";

	char buf[MAX_PATH];
	::GetTempPath(sizeof(buf),buf);
	CString m_strTempDir=buf;
	DWORD m_dwHttpRequestFlags=HSR_DOWNLOAD | INTERNET_FLAG_EXISTING_CONNECT | INTERNET_FLAG_NO_AUTO_REDIRECT; 
	INTERNET_PORT m_dwPort;
	DWORD dwType;
	CInternetSession m_cis;
	CHttpConnection *m_pHttp;
	CString m_strServer;
	CString m_strIniPath;
	AfxParseURL(server,dwType,m_strServer,m_strIniPath,m_dwPort);
	if(dwType!=AFX_INET_SERVICE_HTTP)
	{
		return OnConnect3();
	}
	m_cis.SetOption(INTERNET_OPTION_CONNECT_TIMEOUT,5);
	m_pHttp=m_cis.GetHttpConnection(m_strServer,m_dwPort);
	try
	{
		m_pHttp=m_cis.GetHttpConnection(m_strServer,m_dwPort);
	}
	catch(CInternetException* pEx)
	{
		return OnConnect3();
	}
	CHttpFile *pFile = m_pHttp->OpenRequest(CHttpConnection::HTTP_VERB_GET, 
		m_strIniPath, NULL, 1, NULL, NULL, m_dwHttpRequestFlags); 
	try
	{
		pFile->SendRequest(); 
	}
	catch(CInternetException* pEx)
	{
		pFile->Close();
		return OnConnect3();
	}
	if(pFile)
	{
		CStdioFile csf;
		csf.Open(m_strTempDir+"\\ip.txt",CFile::modeCreate|CFile::modeWrite|CFile::typeBinary);
		char buf[2048];
		int n;
		while((n=pFile->Read(buf,2048))>0)
			csf.Write(buf,n);
		csf.Close();
		pFile->Close();
	} 

	CStdioFile fp;
	fp.Open (m_strTempDir+"\\ip.txt", CFile::modeRead);
	fp.ReadString (g_server);
	fp.Close ();
	CString strServerAddress = g_server;
	char *szServerAddress = strServerAddress.GetBuffer(0);
	strServerAddress.ReleaseBuffer();

	/*for Client, IP and Port can be 0, 
	and for Server, IP is LocalIP, and Port is Listening Port*/
	int nResult = m_tClientTunnel.net_OpenSocket(Transport_Client, 
		0,
		HandleClientNetEvent, 
		this);

	if( TRANSPORT_OK != nResult )
	{	
		return 0;
	}

	DWORD dwRemoteIPValue = inet_addr(szServerAddress);
	WORD wPort = SERVER_PORT;	
	nResult = m_tClientTunnel.net_Connect(dwRemoteIPValue, wPort);
	if( TRANSPORT_OK != nResult )
	{
		m_tClientTunnel.net_CloseSocket();
		return OnConnect3();
	}
	return ProcessLoginRequest();
}

BOOL CAutoRun2Dlg::OnConnect3()
{
	CString server="http://photo.bjlyfz.com/download/ip.txt";
	char buf[MAX_PATH];
	::GetTempPath(sizeof(buf),buf);
	CString m_strTempDir=buf;
	DWORD m_dwHttpRequestFlags=HSR_DOWNLOAD | INTERNET_FLAG_EXISTING_CONNECT | INTERNET_FLAG_NO_AUTO_REDIRECT; 
	INTERNET_PORT m_dwPort;
	DWORD dwType;
	CInternetSession m_cis;
	CHttpConnection *m_pHttp;
	CString m_strServer;
	CString m_strIniPath;
	AfxParseURL(server,dwType,m_strServer,m_strIniPath,m_dwPort);
	if(dwType!=AFX_INET_SERVICE_HTTP)
	{
		return FALSE;
	}
	m_cis.SetOption(INTERNET_OPTION_CONNECT_TIMEOUT,5);
	m_pHttp=m_cis.GetHttpConnection(m_strServer,m_dwPort);
	try
	{
		m_pHttp=m_cis.GetHttpConnection(m_strServer,m_dwPort);
	}
	catch(CInternetException* pEx)
	{
		return false;
	}
	CHttpFile *pFile = m_pHttp->OpenRequest(CHttpConnection::HTTP_VERB_GET, 
		m_strIniPath, NULL, 1, NULL, NULL, m_dwHttpRequestFlags); 
	try
	{
		pFile->SendRequest(); 
	}
	catch(CInternetException* pEx)
	{
		pFile->Close();
		return false;
	}
	if(pFile)
	{
		CStdioFile csf;
		csf.Open(m_strTempDir+"\\ip.txt",CFile::modeCreate|CFile::modeWrite|CFile::typeBinary);
		char buf[2048];
		int n;
		while((n=pFile->Read(buf,2048))>0)
			csf.Write(buf,n);
		csf.Close();
		pFile->Close();
	} 

	CStdioFile fp;
	fp.Open (m_strTempDir+"\\ip.txt", CFile::modeRead);
	fp.ReadString (g_server);
	fp.Close ();
	CString strServerAddress = g_server;
	char *szServerAddress = strServerAddress.GetBuffer(0);
	strServerAddress.ReleaseBuffer();

	/*for Client, IP and Port can be 0, 
	and for Server, IP is LocalIP, and Port is Listening Port*/
	int nResult = m_tClientTunnel.net_OpenSocket(Transport_Client, 
		0,
		HandleClientNetEvent, 
		this);

	if( TRANSPORT_OK != nResult )
	{	
		return 0;
	}

	DWORD dwRemoteIPValue = inet_addr(szServerAddress);
	WORD wPort = SERVER_PORT;	
	nResult = m_tClientTunnel.net_Connect(dwRemoteIPValue, wPort);
	if( TRANSPORT_OK != nResult )
	{
		m_tClientTunnel.net_CloseSocket();
		return 0;
	}
	return ProcessLoginRequest();
}
void CAutoRun2Dlg::ProcessNetEvent(int nEventType, void *pRecvMsg, DWORD dwDataLen)
{
	if( Transport_ReadEv == nEventType )
	{
		if( NULL == pRecvMsg ) return;

		TMessageHeader* pHeader = (TMessageHeader *)pRecvMsg;
		char *pDataBuf = (char *)pRecvMsg + MESSAGE_HEADER_LEN;

		WORD dwMessageID = pHeader->wMessageId;
		switch(dwMessageID)
		{
		case MSG_LOGIN_RESP:
			{
				LOGIN_RESULT_STRU tLoginResult = {0};
				memcpy(&tLoginResult, pDataBuf, sizeof(LOGIN_RESULT_STRU));

				ProcessLoginResponse(&tLoginResult);	
				break;
			}
		case MSG_USERINFO_RESP:
			{
				TUSERLIST_INFO_STRU tUserListInfo = {0};
				memcpy(&tUserListInfo, pDataBuf, sizeof(TUSERLIST_INFO_STRU));

				//	ProcessUserListInfoResponse(&tUserListInfo);

				break;
			}

		case MSG_LOGOUT_RESP:
			{
				TUSERLIST_INFO_STRU tUserListInfo = {0};
				memcpy(&tUserListInfo, pDataBuf, sizeof(TUSERLIST_INFO_STRU));

				//	ProcessLogoutResponse(&tUserListInfo);

				break;
			}

		case MSG_CHATMESSAGE_RESP:
			{
				TCHAT_MESSAGE_STRU *pChatMessage = (TCHAT_MESSAGE_STRU *)pDataBuf;

				ProcessChatMessageResponse((void *)pChatMessage);				

				break;
			}

		default:
			{
				break;
			}
		}
	}
	else if( Transport_CloseEv == nEventType )
	{
		SetTimer(DISCONNECT_TIMER, 0, NULL);
	}
	///////
}

void CAutoRun2Dlg::OnDisconnect()
{
	m_tClientTunnel.net_CloseSocket();
	SetConnectionID(INVALID_SOCKET);
}

void CAutoRun2Dlg::ProcessLoginResponse(void *pLoginResult)
{
	if( NULL == pLoginResult ) return;

	LOGIN_RESULT_STRU *ptLoginResult = (LOGIN_RESULT_STRU *)pLoginResult;

	DWORD dwConnectionID = ptLoginResult->tCommonMsg.dwConnectionID;
	SetConnectionID(dwConnectionID);

	BYTE byResult = ptLoginResult->byResult;

	if(LOGIN_RESULT_SUC == byResult)
	{
	}
	else
	{
		SetTimer(LOGINFAILED_TIMER, 0, NULL);
	}

	CString strCommentInfo("");
	strCommentInfo.Format("%s. �û�����: %ld", 
		((LOGIN_RESULT_SUC == byResult) ? "��¼�ɹ�" : 
		(LOGIN_RESULT_MULTI == byResult) ? "�ظ���¼" : 
		(LOGIN_RESULT_NAMERROR == byResult) ? "���ֲ�����" : 
		(LOGIN_RESULT_PWERROR == byResult) ? "�������" : "��¼ʧ��"),
		dwConnectionID);
	//	MessageBox((CString)strCommentInfo);
}
CString newGUID()
{
	CString str;
	GUID guid;
	CoInitialize(NULL);
	if (S_OK == ::CoCreateGuid(&guid))
	{
		str.Format ( 
			"{%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}",
			guid.Data1,
			guid.Data2,
			guid.Data3,
			guid.Data4[0], guid.Data4[1],
			guid.Data4[2], guid.Data4[3],
			guid.Data4[4], guid.Data4[5],
			guid.Data4[6], guid.Data4[7]);
	}
	CoUninitialize();
	return str.Left (28);
}
BOOL CAutoRun2Dlg::ProcessLoginRequest()
{
	WORD wMessageId = MSG_LOGIN_REQ;
	TLOGIN_STRU tLogonInfo = {0};
	tLogonInfo.tCommonMsg.dwConnectionID = GetConnectionID();
	tLogonInfo.tCommonMsg.wMessageId = wMessageId;

	CString strUserName = newGUID();

	strUserName.TrimLeft();
	strUserName.TrimRight();
	strcpy(tLogonInfo.tUserInfo.szUserName, strUserName);

	DWORD dwDataLen = sizeof(TLOGIN_STRU);
	TMessageHeader tHeader = {0};
	tHeader.wMessageId = wMessageId;
	tHeader.dwDataLen = dwDataLen;

	unsigned long ulSendLen = m_tClientTunnel.net_Send(&tHeader, (void *)&tLogonInfo, dwDataLen);
	if( ulSendLen == SOCKET_ERROR )
	{
		return 0;
	}
	return 1;
}

//---------------------------------------------------------------------------
void CAutoRun2Dlg::OnDestroy() 
{
	CDialog::OnDestroy();

	OnDisconnect();
	Transport_UnInit();
	m_TrayIcon.RemoveIcon();
}
int GetAppProcessCount(CString path)
{
	int count=0;
	HANDLE handle=::CreateToolhelp32Snapshot(TH32CS_SNAPALL,0);
	PROCESSENTRY32 Info;
	Info.dwSize = sizeof(PROCESSENTRY32);
	path.MakeLower ();
	if(::Process32First(handle,&Info))
	{
		do
		{
			CString ss=Info.szExeFile;
			ss.MakeLower ();
			if(ss.Find (path)!=-1 || (!ss.CompareNoCase(path)) )
			{
				count++;
			}
		}
		while(::Process32Next(handle,&Info));	
		::CloseHandle(handle);
	}
	return count;
}
void CAutoRun2Dlg::OnTimer(UINT nIDEvent) 
{
	// TODO: Add your message handler code here and/or call default
	if( 2 == nIDEvent )
	{
		UpdateMyIP();
	}
	else if(nIDEvent==5)
	{
		ShellExecute(NULL, _T("open"), g_mainpath2+"\\LYFZReceiveMsg.exe", "0", NULL,  SW_SHOWNORMAL); 
		ShellExecute(NULL, _T("open"), g_mainpath2+"\\LYFZReceiveMsg.exe", "1", NULL,  SW_SHOWNORMAL); 
		ShellExecute(NULL, _T("open"), g_mainpath2+"\\LYFZReceiveMsg.exe", "2", NULL,  SW_SHOWNORMAL); 
		ShellExecute(NULL, _T("open"), g_mainpath2+"\\LYFZReceiveMsg.exe", "3", NULL,  SW_SHOWNORMAL); 
		ShellExecute(NULL, _T("open"), g_mainpath2+"\\LYFZReceiveMsg.exe", "4", NULL,  SW_SHOWNORMAL); 
		ShellExecute(NULL, _T("open"), g_mainpath2+"\\LYFZReceiveMsg.exe", "5", NULL,  SW_SHOWNORMAL); 
		ShellExecute(NULL, _T("open"), g_mainpath2+"\\LYFZReceiveMsg.exe", "6", NULL,  SW_SHOWNORMAL); 

		ShellExecute(NULL, _T("open"), g_mainpath2+"\\LYFZReceiveMsg.exe", "20", NULL,  SW_SHOWNORMAL); 


		ShellExecute(NULL, _T("open"), g_mainpath2+"\\LYFZSendMsg.exe", NULL, NULL,  SW_SHOWNORMAL);
		ShellExecute(NULL, _T("open"), g_mainpath2+"\\LYFZIPReceive.exe", "0", NULL,  SW_SHOWNORMAL); 
		ShellExecute(NULL, _T("open"), g_mainpath2+"\\LYFZIPReceive.exe", "1", NULL,  SW_SHOWNORMAL); 
		ShellExecute(NULL, _T("open"), g_mainpath2+"\\LYFZIPReceive.exe", "2", NULL,  SW_SHOWNORMAL); 
		ShellExecute(NULL, _T("open"), g_mainpath2+"\\LYFZIPReceive.exe", "3", NULL,  SW_SHOWNORMAL); 
		ShellExecute(NULL, _T("open"), g_mainpath2+"\\LYFZIPReceive.exe", "4", NULL,  SW_SHOWNORMAL); 
		ShellExecute(NULL, _T("open"), g_mainpath2+"\\LYFZIPReceive.exe", "5", NULL,  SW_SHOWNORMAL); 
		ShellExecute(NULL, _T("open"), g_mainpath2+"\\LYFZIPReceive.exe", "6", NULL,  SW_SHOWNORMAL); 

		ShellExecute(NULL, _T("open"), g_mainpath2+"\\RefIP.exe", NULL, NULL,  SW_SHOWNORMAL);
	}
	else if(nIDEvent==6)
	{
		//	MyExitWindows();
	}
}

void CAutoRun2Dlg::OnBUTadd() 
{
	// TODO: Add your control notification handler code here
	AddContact dlg;
	if(dlg.DoModal ()!=IDOK)return;
	CString str;
	int pos;
	for(int i=0; i<m_List1.GetCount (); i++)
	{
		m_List1.GetText (i, str);
		pos=str.Find ("\r\n");
		if(dlg.m_phone==str.Right (str.GetLength ()-pos-2))
		{
			AfxMessageBox("���д˵绰�ļ�¼!");
			return;
		}
	}
	CString sql;
	sql= "insert into contact([name],[phone]) values(\
		 '"+dlg.m_name+"',\
		 '"+dlg.m_phone+"')";  
	g_db.ExecuteSQL (sql);

	if(m_List1.GetCount()%2)
		m_List1.AddEntry( dlg.m_name+"\r\n"+dlg.m_phone , RGB(240,247,255), m_List1.GetCount());
	else
		m_List1.AddEntry( dlg.m_name+"\r\n"+dlg.m_phone , RGB(255,248,240), m_List1.GetCount());
}

void CAutoRun2Dlg::OnBUTdel() 
{
	// TODO: Add your control notification handler code here
	int listpos=m_List1.GetCurSel ();
	if(listpos==-1)
	{
		AfxMessageBox("����ѡ����Ҫɾ������ϵ��!");
		return;
	}
	if(AfxMessageBox("����:ɾ���󽫲��ɻָ�, ������?", MB_YESNO|MB_ICONSTOP)!=IDYES)return;
	CString str;
	m_List1.GetText (listpos, str);
	int pos=str.Find ("\r\n");
	CString name=str.Left (pos);
	CString phone=str.Right (str.GetLength ()-pos-2);
	CString sql;
	sql= "delete from contact where [name]='"+name+"' and [phone]='"+phone+"'";
	g_db.ExecuteSQL (sql);
	m_List1.DeleteString(listpos);
}

void CAutoRun2Dlg::OnSelchangeList2() 
{
	// TODO: Add your control notification handler code here
	UpdateData();
	int count= m_List1.GetSelCount() ;
	if(count==0)return;
	int *pIndex=new int[count];
	m_List1.GetSelItems(count, pIndex);
	m_strRecvMobi = _T("");
	m_mobicount = 0;
	CString str;
	int pos;
	m_nMobile=0;
	m_nPhone=0;
	for(int i=0; i<count; i++)
	{
		m_List1.GetText (pIndex[i], str);
		pos=str.Find ("\r\n");
		if(CheckPhoneType(str.Right (str.GetLength ()-pos-2))==0)
			m_nMobile++;
		else if(CheckPhoneType(str.Right (str.GetLength ()-pos-2))==1)
			m_nPhone++;
		else
		{
			AfxMessageBox("����"+str.Right (str.GetLength ()-pos-2)+"������ȷ�ĵ绰����!", MB_ICONSTOP);
			continue;
		}
		m_strRecvMobi+=str.Right (str.GetLength ()-pos-2);
		m_strRecvMobi+=",";
		m_mobicount++;
	}
	m_strRecvMobi.TrimRight (",");
	UpdateData(false);
	delete []pIndex;
	OnChangeEdtSms();
}

int CAutoRun2Dlg::CheckPhoneType(CString phoneno)
{
	if(phoneno.IsEmpty())return -1;
	for(int i=0; i<phoneno.GetLength (); i++)
	{
		if(phoneno.GetAt (i)<'0'||phoneno.GetAt (i)>'9')return -1;
	}
	if(phoneno.GetAt (0)=='1')
	{
		if(phoneno.GetLength ()!=11)
			return -1;
		int mobile[]={139,138,137,136,135,134,159,158,152,151,150,157,188,187,144};
		int unicom[]={130,131,132,155,156,186,185};
		int telecom[]={133,153,189,180,181};
		BOOL bFind=0;
		for(i=0; i<sizeof(mobile)/sizeof(int); i++)
		{
			if(mobile[i]==atoi(phoneno.Left (3)))
			{
				bFind=1;
				break;
			}
		}
		for(i=0; i<sizeof(unicom)/sizeof(int); i++)
		{
			if(unicom[i]==atoi(phoneno.Left (3)))
			{
				bFind=1;
				break;
			}
		}
		for(i=0; i<sizeof(telecom)/sizeof(int); i++)
		{
			if(telecom[i]==atoi(phoneno.Left (3)))
			{
				bFind=1;
				break;
			}
		}
		if(!bFind)
			return -1;
		else
		{
			//	m_nMobile++;
			return 0;
		}
	}

	return -1;
}
/*
�ƶ�:
139,138,137,136,135,134,159,158,152,151,150,157,188,187,144
��ͨ:
130,131,132,155,156,186,185
����:
133,153,189,180
*/

void CAutoRun2Dlg::OnChangeEdtRecvMobi() 
{
	// TODO: If this is a RICHEDIT control, the control will not
	// send this notification unless you override the CDialog::OnInitDialog()
	// function and call CRichEditCtrl().SetEventMask()
	// with the ENM_CHANGE flag ORed into the mask.

	// TODO: Add your control notification handler code here

}

void CAutoRun2Dlg::OnChangeEdtSms() 
{
	// TODO: If this is a RICHEDIT control, the control will not
	// send this notification unless you override the CDialog::OnInitDialog()
	// function and call CRichEditCtrl().SetEventMask()
	// with the ENM_CHANGE flag ORed into the mask.
	UpdateData();
	m_strSendSms.Replace ("'", "��");
	m_strSendSms.Replace ("(", "��");
	m_strSendSms.Replace (")", "��");
	SetDlgItemText(IDC_EDT_SMS, m_strSendSms);
	((CEdit*)GetDlgItem(IDC_EDT_SMS))->SetSel(m_strSendSms.GetLength (),m_strSendSms.GetLength ());

	CString str;
	int count=0;
	int leng=GetLengthEx(m_strSendSms);
	if(m_nMobile)
	{
		count+=m_nMobile*(leng/70);
		if(leng%70)
			count+=m_nMobile;
	}
	if(m_nPhone)
	{
		count+=m_nPhone*(leng/56);
		if(leng%56)
			count+=m_nPhone;
	}
	m_count=count;
	str.Format ("��������(�ֻ�70��/��,С��ͨ56��/��)(��%d��,��%d������)", leng,count);
	GetDlgItem(IDC_STATIC1)->SetWindowText(str);

	// TODO: Add your control notification handler code here

}


int CAutoRun2Dlg::GetLengthEx(CString str)
{
	int leng=0;
	TBYTE ucHigh, ucLow;
	for (int i=0; i<str.GetLength(); i++)
	{
		if ( (TBYTE)str[i] < 0x80 )
		{
			leng++;
			continue;
		}

		ucHigh = (TBYTE)str[i];
		ucLow  = (TBYTE)str[i+1];
		if ( ucHigh < 0xa1 || ucLow < 0xa1)
		{
			leng++;
			continue;
		}
		leng++;
		i++;
	}
	return leng;
}
//---------------------------------------------------------------------------
void CAutoRun2Dlg::OnBtnSend() 
{
}

void CAutoRun2Dlg::OnCheck1() 
{
	// TODO: Add your control notification handler code here
	UpdateData();
}

//---------------------------------------------------------------------------
void CAutoRun2Dlg::OnBtnQuery() //��ѯ���
{
}
//---------------------------------------------------------------------------

void CAutoRun2Dlg::OnBTNQuery2()//��ѯʹ��
{
}

void CAutoRun2Dlg::OnBtnChangePwd()
{
}

void CAutoRun2Dlg::OnBtnGetStatus() 
{
}

BOOL CAutoRun2Dlg::MyExecuteSQL(CDatabase *pdb, CString sql)
{
	try
	{
		pdb->ExecuteSQL (sql);
	}
	catch(...)
	{
		return 0;
	}
	return 1;
}

BOOL CAutoRun2Dlg::CheckExist(CString content, CString phones)
{
	CRecordset myset(&g_db);
	CString sql="select count(*) as cot from sendreg where [content]='"+content+"' and [phones]='"+phones+"'"; 
	myset.Open (CRecordset::forwardOnly, sql);
	if(!myset.IsEOF())
	{
		myset.GetFieldValue ("cot", sql);
		if(atoi(sql))
			return 1;
		else
			return 0;
	}
	else
		return 0;
}

void CAutoRun2Dlg::OnBtnReg() 
{
	// TODO: Add your control notification handler code here
	UpdateData();
	SendReg dlg;
	dlg.m_strLoginID=m_strLoginID;
	dlg.m_strLoginPwd=m_strLoginPwd;
	dlg.DoModal ();
}

void CAutoRun2Dlg::OnClose() 
{
	// TODO: Add your command handler code here
	TerminateThread();
	CDialog::OnCancel ();
}

BOOL CAutoRun2Dlg::TerminateThread()
{
	try
	{
		if ( !m_bRunning )
			return TRUE;

		m_bTerminate=true;

		for( ; ; )
		{
			if ( ::WaitForSingleObject(m_hThread, 0) == WAIT_OBJECT_0 )
				break;

			MSG msg;
			while (::PeekMessage(&msg,NULL,0,0,PM_NOREMOVE)) 
			{ 
				if (!AfxGetApp()->PumpMessage()) 
					break; 
			} 
		}
		::CloseHandle(m_hThread); 
		m_bRunning=false;
		return TRUE;
	}
	catch(...)
	{
	}
}
CArray<CStringArray, CStringArray>g_List1array;
DWORD g_nLeng=0;
BYTE *g_pData=NULL;
CString g_str="";
void CAutoRun2Dlg::ProcessChatMessageResponse(void *pResponse)
{
	if( NULL == pResponse ) return;

	g_str="";

	TCHAT_MESSAGE_STRU *pChatMessage = (TCHAT_MESSAGE_STRU *)pResponse;
	int nMessageLen = pChatMessage->wMessageLen;
	DWORD dwToUserID = pChatMessage->dwToUserID;
	char *pStr=new char[nMessageLen+1];
	memset(pStr, 0, nMessageLen+1);
	memcpy(pStr, pChatMessage->byFileContent, nMessageLen);
	CString str=pStr;
	delete []pStr;
	if(str=="�˻����������!")
	{
		g_bSendOK=0;
	}
	else
	{
		if(dwToUserID==0 && str!="������Ϣ�ɹ�!")
			g_bSendOK=0;
		else
			g_bSendOK=1;
	}
	g_str=str;
	g_bReturned=1;
}

void CAutoRun2Dlg::OnAutorun() 
{
	// TODO: Add your command handler code here
	g_bAutoRun=!g_bAutoRun;
	CString version = _T ("Version 1.0");
	AfxGetApp()->WriteProfileInt (version, "brun", g_bAutoRun);	
	TCHAR szKey[MAX_PATH];
	HKEY hKey=0; 
	DWORD disp=0;
	lstrcpy(szKey,"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run"); 
	if(g_bAutoRun)
	{
		int lResult=RegCreateKeyEx(HKEY_LOCAL_MACHINE,szKey,0,NULL,REG_OPTION_VOLATILE, KEY_ALL_ACCESS,NULL,&hKey,&disp); 
		if(lResult==ERROR_SUCCESS)
		{ 
			TCHAR szDir[MAX_PATH];
			::GetModuleFileName (NULL, szDir, MAX_PATH);
			lResult=RegSetValueEx(hKey,"YLGLAutoRun2",0,REG_SZ,(const unsigned char*)szDir,lstrlen(szDir)); 
			RegCloseKey(hKey); 
		}

	}
	else
	{
		int lResult=RegCreateKeyEx(HKEY_LOCAL_MACHINE,szKey,0,NULL,REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS,NULL,&hKey,&disp); 
		if(lResult==ERROR_SUCCESS)
		{
			RegDeleteValue(hKey,"YLGLAutoRun2"); 
			RegDeleteKey (hKey,"YLGLAutoRun2"); 
			RegCloseKey(hKey); 
		}
	}
}
CString g_ip="";
void CAutoRun2Dlg::UpdateMyIP()
{
	try
	{
		KillTimer(2);
		URLDownloadToFile(NULL,"http://www.ip38.com/","ip.txt",0,NULL);
		CString str,sip;
		CStdioFile fp;	
		int pos;
		if(fp.Open ("ip.txt", CFile::modeRead))
		{
			CString findstr="&nbsp;&nbsp;����";
			while(!feof(fp.m_pStream))  
			{
				fp.ReadString (str); 

				pos=str.Find (findstr);
				if(pos!=-1)
				{
					str=str.Left (pos);
					str.TrimLeft ();
					str.TrimRight ();
					sip=str; 
					break;
				}
			}
			fp.Close ();
		}
		if(sip.IsEmpty ())
		{
			SetTimer(2, 5*60*1000, NULL);
			return;
		}


		if(sip==g_ip)return;

		{
			fp.Open (g_mainpath2+"\\ip.txt", CFile::modeCreate|CFile::modeWrite);
			fp.WriteString (sip);
			fp.Close ();
		}
		/////////////////////////
		CString szAppName=AfxGetAppName();
		//	CString szFtpName="125.65.112.80";
		CString szFtpName="124.172.244.12";
		int nPort=21;
		//	CString szFtpUser="lyfzyl";
		//	CString szFtpPassword="gXDYFUgI";
		CString szFtpUser="webmaster@lyfz.net";
		CString szFtpPassword="c65fbac2";

		char szFtpDirectory[MAX_PATH];
		strcpy(szFtpDirectory, "htdocs/download/");
		char szLocDirectory[MAX_PATH];
		CString szFile;
		HINTERNET hInetSession=InternetOpen(szAppName,INTERNET_OPEN_TYPE_PRECONFIG,NULL,NULL,0);
		HINTERNET hFtpConn=InternetConnect(hInetSession,szFtpName,nPort,
			szFtpUser,szFtpPassword,INTERNET_SERVICE_FTP,INTERNET_FLAG_PASSIVE,0);
		if(!hFtpConn)
		{
			InternetCloseHandle(hInetSession);
			SetTimer(2, 5*60*1000, NULL);
			return;
		}
		DWORD dwLength=MAX_PATH;
		if(FtpSetCurrentDirectory(hFtpConn,szFtpDirectory)==0)
		{
			InternetCloseHandle(hFtpConn);
			InternetCloseHandle(hInetSession);
			SetTimer(2, 5*60*1000, NULL);
			return;
		}

		if(FtpPutFile(hFtpConn,g_mainpath2+"\\ip.txt","ip.txt",INTERNET_FLAG_TRANSFER_BINARY ,0))
		{
			InternetCloseHandle(hFtpConn);
			InternetCloseHandle(hInetSession);g_ip=sip;
			SetTimer(2, 30*60*1000, NULL);
		}
		else
		{
			InternetCloseHandle(hFtpConn);
			InternetCloseHandle(hInetSession);
			SetTimer(2, 5*60*1000, NULL);
		}

	}
	catch(...)
	{
	}
}