局域网即时聊天系统 项目个人责任原稿

来源:互联网 发布:豆瓣与知乎哪个实用 编辑:程序博客网 时间:2024/04/20 09:47
// MFCNetChatDlg.cpp : 实现文件// #include "stdafx.h"#include "MFCNetChat.h"#include "MFCNetChatDlg.h"#include "CsplashWnd.h" #include "Register.h"#include "Forget.h"#include "Login.h"  #ifdef _DEBUG#define new DEBUG_NEW#endif  // CMFCNetChatDlg 对话框  CMFCNetChatDlg::CMFCNetChatDlg(CWnd* pParent /*=NULL*/)    : CDialog(CMFCNetChatDlg::IDD, pParent)    , m_LoginID(0)    , m_LoginPwd(_T(""))    , m_IsLogin(false)    , m_nWidth(0){    m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);} void CMFCNetChatDlg::DoDataExchange(CDataExchange* pDX){    CDialog::DoDataExchange(pDX);    DDX_Text(pDX, IDC_LOGIN_ID, m_LoginID);    DDX_Text(pDX, IDC_LOGIN_PWD, m_LoginPwd);} BEGIN_MESSAGE_MAP(CMFCNetChatDlg, CDialog)    ON_WM_PAINT()    ON_WM_QUERYDRAGICON()    //}}AFX_MSG_MAP    ON_BN_CLICKED(IDC_BTN_REGISTER, &CMFCNetChatDlg::OnBnClickedBtnRegister)    ON_BN_CLICKED(IDC_BTN_FORGET, &CMFCNetChatDlg::OnBnClickedBtnForget)    ON_BN_CLICKED(IDC_BTN_LOGIN, &CMFCNetChatDlg::OnBnClickedBtnLogin)    ON_BN_CLICKED(IDCANCEL, &CMFCNetChatDlg::OnBnClickedCancel)    ON_WM_CREATE()    ON_WM_TIMER()END_MESSAGE_MAP()  // CMFCNetChatDlg 消息处理程序 BOOL CMFCNetChatDlg::OnInitDialog(){    CDialog::OnInitDialog();     Sleep(2000);     // 设置此对话框的图标。当应用程序主窗口不是对话框时,框架将自动    //  执行此操作    SetIcon(m_hIcon, TRUE);         // 设置大图标    SetIcon(m_hIcon, FALSE);        // 设置小图标     // TODO: 在此添加额外的初始化代码      if (!AfxOleInit())    {        AfxMessageBox(_T("数据库初始化失败!"));        return false;    }     HRESULT hr;    hr=m_conPtr.CreateInstance(__uuidof(Connection));     if (SUCCEEDED(hr))    {         try        {            m_conPtr->Open(_bstr_t("provider=sqloledb.1; server=172.7.41.31\SQL2005; database=NetChat ")                  , _bstr_t("sa"), _bstr_t("123"), -1);             CString Sqlstr=_T("select *  from  NetChat");            m_rsPtr.CreateInstance(__uuidof(Recordset));//          m_rsPtr->Open(_bstr_t(Sqlstr), m_conPtr.GetInterfacePtr(), adOpenKeyset, adLockPessimistic , adCmdText);            _RecordsetPtr TempPtr;            TempPtr=m_conPtr->Execute( _bstr_t(Sqlstr),NULL, adCmdText );         }        catch (_com_error e)        {            CString errMsg;            errMsg.Format(_T("连接错误,原因:%s"),e.ErrorMessage());            AfxMessageBox( errMsg);            return FALSE;        }             }      return TRUE;  // 除非将焦点设置到控件,否则返回 TRUE} // 如果向对话框添加最小化按钮,则需要下面的代码//  来绘制该图标。对于使用文档/视图模型的 MFC 应用程序,//  这将由框架自动完成。 void CMFCNetChatDlg::OnPaint(){    if (IsIconic())    {        CPaintDC dc(this); // 用于绘制的设备上下文         SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);         // 使图标在工作区矩形中居中        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;         // 绘制图标        dc.DrawIcon(x, y, m_hIcon);    }    else    {         CPaintDC dc(this);        if( !m_imgBK.IsNull())             m_imgBK.Destroy();         m_imgBK.Load(_T("54321.jpg"));        if( !m_imgBK.IsNull())             m_imgBK.Draw(dc.m_hDC, 0, 0, 512, 342);          CString str="★欢迎使用本聊天程序,试用阶段!!!★";         dc.TextOut(50,10,str);         CDialog::OnPaint();    }} //当用户拖动最小化窗口时系统调用此函数取得光标//显示。HCURSOR CMFCNetChatDlg::OnQueryDragIcon(){    return static_cast<HCURSOR>(m_hIcon);}    void CMFCNetChatDlg::OnBnClickedBtnRegister(){    // TODO: 在此添加控件通知处理程序代码    CRegister Register;    Register.DoModal();} void CMFCNetChatDlg::OnBnClickedBtnForget(){    // TODO: 在此添加控件通知处理程序代码    CForget Forget;    Forget.DoModal();} void CMFCNetChatDlg::OnBnClickedBtnLogin(){    // TODO: 在此添加控件通知处理程序代码    UpdateData(true);      CString strIP;    char szHostName[128];    if (gethostname(szHostName, 128)==0)    {        struct hostent * pHost;        int i;        pHost = gethostbyname(szHostName);        for (i=0; pHost !=NULL && pHost->h_addr_list[i]!= NULL; i++)        {             int j;            for (j=0; j<pHost->h_length; j++)            {                CString addr;                if (j>=0)                {                     addr.Format(_T("%u"), (unsigned int)((unsigned char*)pHost->h_addr_list[i])[j]);                                     strIP += addr;                    if (j!=pHost->h_length-1)                    {                        strIP += ".";                    }                 }            }        }    }        CString str,str1;     str.Format(_T("select count(ClientID) from NetChat where ClientID=%d"), m_LoginID);    int temp,temp1;    _RecordsetPtr tempPtr, tempPtr1;    tempPtr=m_conPtr->Execute(_bstr_t(str), NULL, adCmdText);    temp=tempPtr->GetCollect(_variant_t((long)0));       if (temp==1 )    {               str1.Format(_T("select count(ClientID) from NetChat where ClientID=%d and ClientPwd='%s'"), m_LoginID, m_LoginPwd);        tempPtr1=m_conPtr->Execute(_bstr_t(str1), NULL, adCmdText);        temp1=tempPtr1->GetCollect(_variant_t((long)0));        if (temp1==0)        {            AfxMessageBox(_T("账号或密码不正确!"));            return;        }     }else{         AfxMessageBox(_T("此账号不存在!"));        return;         }     CString str2;    str2.Format(_T("select Status from NetChat where ClientID=%d "), m_LoginID);    m_rsPtr=m_conPtr->Execute(_bstr_t(str2), NULL, adCmdText);    CString status=m_rsPtr->GetCollect(_variant_t((long)0));    if (!status.Compare("true      "))    {        AfxMessageBox(_T("对不起该用户已登录,请检查您的账号安全!"));        return;    }      CString sql;    sql.Format(_T("update NetChat set TempIP='%s',Status='true' where ClientID=%d"), strIP, m_LoginID);    m_conPtr->Execute(_bstr_t(sql), NULL, adCmdText);    OnOK();     CLogin Login;    Login.DoModal();            } void CMFCNetChatDlg::OnBnClickedCancel(){    // TODO: 在此添加控件通知处理程序代码    OnCancel();} int CMFCNetChatDlg::OnCreate(LPCREATESTRUCT lpCreateStruct){    if (CDialog::OnCreate(lpCreateStruct) == -1)        return -1;     // TODO:  在此添加您专用的创建代码    CSplashWnd::ShowSplashScreen(this);     SetTimer(1,100,NULL);     return 0;} void CMFCNetChatDlg::OnTimer(UINT_PTR nIDEvent){    // TODO: 在此添加消息处理程序代码和/或调用默认值               m_nWidth+=5;        CClientDC dc(this);                 CString str="★欢迎使用本聊天程序,试用阶段!!!★";         CSize sz=dc.GetTextExtent(str);         CRect rect;        rect.left=50;        rect.top=10;        rect.right=m_nWidth+70;        rect.bottom=rect.top+sz.cy;                     dc.SetTextColor(RGB(255,0,0));            dc.DrawText(str,rect,DT_LEFT);             if (m_nWidth>sz.cx)        {            m_nWidth=0;            dc.SetTextColor(RGB(0,255,0));            dc.TextOut(50,10,str);          }                                    CDialog::OnTimer(nIDEvent);}   // Login.cpp : 实现文件// #include "stdafx.h"#include "MFCNetChat.h"#include "Login.h"#include "addfriend.h"#include "chat.h"#include <list>using namespace std; // CLogin 对话框  struct RECVPARAM  {    SOCKET sock;    HWND hwnd;}; struct LISTINFO{    CString GetIP;    HWND hwnd;}; list<LISTINFO> LIST;   IMPLEMENT_DYNAMIC(CLogin, CDialog) CLogin::CLogin(CWnd* pParent /*=NULL*/)    : CDialog(CLogin::IDD, pParent)     , m_IsLogin(false)    , strIP(_T("")){ } CLogin::~CLogin(){} void CLogin::DoDataExchange(CDataExchange* pDX){    CDialog::DoDataExchange(pDX);     DDX_Control(pDX, IDC_TREE1, m_treeCtrl);}  BEGIN_MESSAGE_MAP(CLogin, CDialog)    ON_BN_CLICKED(IDC_BTN_ADD, &CLogin::OnBnClickedBtnAdd)    ON_NOTIFY(NM_DBLCLK, IDC_TREE1, &CLogin::OnNMDblclkTree1)    ON_WM_CLOSE()    ON_MESSAGE(WM_RECV,SEND)    ON_WM_PAINT()    ON_MESSAGE(WM_ADDFRIEND, OnAddFriend)    ON_NOTIFY(NM_RCLICK, IDC_TREE1, &CLogin::OnNMRClickTree1)END_MESSAGE_MAP()  // CLogin 消息处理程序  BOOL CLogin::OnInitDialog(){     CDialog::OnInitDialog();     // TODO:  在此添加额外的初始化     OnGetLocalIP();     HRESULT hr;    hr=m_conPtr.CreateInstance(__uuidof(Connection));     if (SUCCEEDED(hr))    {         try        {            m_conPtr->Open(_bstr_t("provider=sqloledb.1; server=172.7.41.31\SQL2005; database=NetChat ")                  , _bstr_t("sa"), _bstr_t("123"), -1);             CString Sqlstr=_T("select *  from  NetChat");            m_rsPtr.CreateInstance(__uuidof(Recordset));            m_rsPtr->Open(_bstr_t(Sqlstr), m_conPtr.GetInterfacePtr(), adOpenKeyset, adLockPessimistic , adCmdText);            _RecordsetPtr TempPtr;            TempPtr=m_conPtr->Execute( _bstr_t(Sqlstr),NULL, adCmdText );         }        catch (_com_error e)        {            CString errMsg;            errMsg.Format(_T("连接错误,原因:%s"),e.ErrorMessage());            AfxMessageBox( errMsg);            return FALSE;        }     }//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////     m_ImaList.Create(16, 16, ILC_COLOR, 5, 1);     m_ImaList.Add(AfxGetApp()->LoadIcon(IDI_ICON1));   ////0    m_ImaList.Add(AfxGetApp()->LoadIcon(IDI_ICON2));   ////1       m_treeCtrl.ModifyStyle(NULL,TVS_HASBUTTONS | TVS_HASLINES | TVS_LINESATROOT|TVS_EDITLABELS);    m_treeCtrl.SetImageList(&m_ImaList,TVSIL_NORMAL);     hItem=m_treeCtrl.InsertItem(_T("我的好友"),0,NULL,TVI_ROOT);     CString getName;    getName.Format(_T("select ClientName from NetChat where TempIP='%s'"), strIP);    m_rsPtr=m_conPtr->Execute(_bstr_t(getName), NULL, adCmdText);    CString Name=m_rsPtr->GetCollect(_variant_t((long)0));     CString FriendList;    FriendList.Format(_T("select max(Line) from(select FriendName,row_number() over(order by FriendName) as Line from %s) as temp"), Name);    m_rsPtr=m_conPtr->Execute(_bstr_t(FriendList), NULL, adCmdText);    int num=m_rsPtr->GetCollect(_variant_t((long)0));     for (int i=1; i<=num; i++)    {        getName.Format(_T("select FriendName from(select FriendName,row_number() over(order by FriendName) as Line from %s) as temp where temp.Line=%d"), Name, i);        m_rsPtr=m_conPtr->Execute(_bstr_t(getName), NULL, adCmdText);        CString addName;        addName=(CString)m_rsPtr->GetCollect(_variant_t((long)0));        m_treeCtrl.InsertItem(addName, 1, 0, hItem);    }  /////////////////////////////////////////////////////////////////////////////////////本地服务器     m_SvrSocket=socket(AF_INET, SOCK_DGRAM, 0);    if (INVALID_SOCKET==m_SvrSocket)    {        AfxMessageBox(_T("套接字创建失败!"));        return false;    }    SOCKADDR_IN AddrSvr;    AddrSvr.sin_family=AF_INET;    AddrSvr.sin_port=htons(3000);    AddrSvr.sin_addr.S_un.S_addr=htonl(INADDR_ANY);          int retval;    retval =bind(m_SvrSocket, (SOCKADDR*)&AddrSvr, sizeof(SOCKADDR));     if (SOCKET_ERROR==retval)    {        closesocket(m_SvrSocket);        MessageBox(_T("绑定失败!"));        return false;    }      RECVPARAM *pRecvParam=new RECVPARAM;    pRecvParam->hwnd=m_hWnd;    pRecvParam->sock=m_SvrSocket;    HANDLE hThread=CreateThread(NULL, 0, ThreadProc, (LPVOID)pRecvParam, 0, NULL);    CloseHandle(hThread); ////////////////////////////////////////////////////////////////////////////////////////     return TRUE;  // return TRUE unless you set the focus to a control    // 异常: OCX 属性页应返回 FALSE3005} void CLogin::OnBnClickedBtnAdd()/////////////////////////////////////////////////////////////////////////////未添加{    // TODO: 在此添加控件通知处理程序代码     CAddFriend add;    add.DoModal();} void CLogin::OnNMDblclkTree1(NMHDR *pNMHDR, LRESULT *pResult){    // TODO: 在此添加控件通知处理程序代码      CString str;    HTREEITEM item=m_treeCtrl.GetSelectedItem();    str=m_treeCtrl.GetItemText(item);      if (!str.Compare(_T("我的好友")))    {        return;    } /////////////////////////////////////////////////获取聊天对象的IP地址和端口号    CString sql;    sql.Format(_T("select TempIP from NetChat where ClientName='%s'"), str);    m_rsPtr=m_conPtr->Execute(_bstr_t(sql), NULL, adCmdText);     CString strIP1=(CString)m_rsPtr->GetCollect(_variant_t((long)0));   ///////////////////////////////////////////////////////////////////////////////     CChat *chat=new CChat(this);    chat->Create(IDD_CHAT,this);    chat->ShowWindow(SW_SHOW);     char *temp=new char[128];    memset(temp, 0, 128);    strcpy(temp, strIP1); ////////////////////////////////////////////////////////////////////////////////LIST容器存储IP及聊天框窗口句柄     LISTINFO listinfo;    listinfo.GetIP=strIP1;    listinfo.hwnd=chat->m_hWnd;    LIST.push_front(listinfo);      ////////////////////////////////////////////////////////////////////////////////    chat->SendMessage(WM_MSG_IP, 0, (LPARAM)temp);     *pResult = 0;} void CLogin::OnClose(){    // TODO: 在此添加消息处理程序代码和/或调用默认值     CString sql;    sql.Format(_T("update NetChat set TempIP='',Status='false' where TempIP='%s'"), strIP);    m_conPtr->Execute(_bstr_t(sql), NULL, adCmdText);     WSACleanup();    CDialog::OnClose(); }  DWORD WINAPI CLogin::ThreadProc(LPVOID lParam){     SOCKET sock=((RECVPARAM*)lParam)->sock;    HWND hwnd=((RECVPARAM*)lParam)->hwnd;    SOCKADDR_IN addrFrom;    int len=sizeof(SOCKADDR);     char recvbuf[1024];    memset(recvbuf, 0, 1024);      int retval;    while(1){         retval=recvfrom(sock, recvbuf, 1024, 0, (SOCKADDR*)&addrFrom, &len);        if (SOCKET_ERROR==retval)        {            break;        }        CString *pstr=new CString;        pstr->Format(_T("%s"), recvbuf);        CString *pstr1=new CString;        pstr1->Format(_T("%s"), inet_ntoa(addrFrom.sin_addr));        ::SendMessage(hwnd, WM_RECV, (WPARAM)pstr1, (LPARAM)pstr);    }       return 0;}    LRESULT CLogin::SEND(WPARAM wParam, LPARAM lParam){     CString* temp=(CString*)lParam;    CString* tempIP=(CString*)wParam;    m_recv=new CChat(this);     list<LISTINFO>::const_iterator p=LIST.begin();    while(p!=LIST.end()){         if ((*p).GetIP==*tempIP)        {            m_hwnd=(*p).hwnd;            break;        }    }    ::SendMessage(m_hwnd, WM_SEND, (WPARAM)tempIP, (LPARAM)temp);      return LRESULT();}   void CLogin::OnGetLocalIP(void){     char szHostName[128];    if (gethostname(szHostName, 128)==0)    {        struct hostent * pHost;        int i;        pHost = gethostbyname(szHostName);        for (i=0; pHost !=NULL && pHost->h_addr_list[i]!= NULL; i++)        {             int j;            for (j=0; j<pHost->h_length; j++)            {                CString addr;                if (j>=0)                {                     addr.Format(_T("%u"), (unsigned int)((unsigned char*)pHost->h_addr_list[i])[j]);                                     strIP += addr;                    if (j!=pHost->h_length-1)                    {                        strIP += ".";                    }                 }            }        }    }} void CLogin::OnPaint(){    CPaintDC dc(this); // device context for painting    // TODO: 在此处添加消息处理程序代码    // 不为绘图消息调用 CDialog::OnPaint()    if( !m_imgBK.IsNull()) m_imgBK.Destroy();     m_imgBK.Load(_T("MaiFormBG.bmp"));    if( !m_imgBK.IsNull())         m_imgBK.Draw(dc.m_hDC, 0, 0, 540, 490);       CBitmap bitmap;    bitmap.LoadBitmap(MAKEINTRESOURCE(IDB_BITMAP16));     CDC memDC;    memDC.CreateCompatibleDC(&dc);    CBitmap *pOldBitmap=memDC.SelectObject(&bitmap);     CRect rect;    GetClientRect(&rect);     dc.BitBlt( 20, 15, rect.Width(), rect.Height(), &memDC, 0, 0, SRCCOPY);}   LRESULT CLogin::OnAddFriend(WPARAM wParam, LPARAM lParam){         int tempID=(int)lParam;    CString str;    str.Format(_T("select ClientName from NetChat where ClientID=%d"), tempID);    m_rsPtr=m_conPtr->Execute(_bstr_t(str), NULL, adCmdText);    CString name=(CString)m_rsPtr->GetCollect(_variant_t((long)0));      CString getName;    getName.Format(_T("select ClientName from NetChat where TempIP='%s'"), strIP);    m_rsPtr=m_conPtr->Execute(_bstr_t(getName), NULL, adCmdText);    CString Name=(CString)m_rsPtr->GetCollect(_variant_t((long)0));     CString AddFriend;    AddFriend.Format(_T("insert into %s(FriendName) values('%s')"), Name, name);    m_rsPtr=m_conPtr->Execute(_bstr_t(AddFriend), NULL ,adCmdText);     m_treeCtrl.InsertItem( name, 0, NULL, hItem);         return LRESULT();}  void CLogin::OnNMRClickTree1(NMHDR *pNMHDR, LRESULT *pResult){    // TODO: 在此添加控件通知处理程序代码    *pResult = 0;}    // #include "stdafx.h"#include "MFCNetChat.h"#include "Chat.h"#include <atlsimpstr.h>#include <iostream> using namespace std;  // CChat 对话框 struct RECVPARAM  {    SOCKET sock;    HWND hwnd;};  IMPLEMENT_DYNAMIC(CChat, CDialog) CChat::CChat(CWnd* pParent /*=NULL*/)    : CDialog(CChat::IDD, pParent)    , m_Send(_T(""))    , m_Recv(_T(""))    , Port(0)    , m_RecvIP(_T(""))    , m_RecvStr(_T("")){ } CChat::~CChat(){} void CChat::DoDataExchange(CDataExchange* pDX){    CDialog::DoDataExchange(pDX);    DDX_Text(pDX, IDC_EDIT_SEND, m_Send);    DDX_Text(pDX, IDC_EDIT_RECV, m_Recv);}  BEGIN_MESSAGE_MAP(CChat, CDialog)    ON_WM_PAINT()    ON_BN_CLICKED(IDC_BTN_ENTER, &CChat::OnBnClickedBtnEnter)    ON_MESSAGE(WM_MSG_IP,OnRecvIP)    ON_MESSAGE(WM_SEND,OnRecvShow)    ON_BN_CLICKED(IDC_BTN_SENDFILE, &CChat::OnBnClickedBtnSendfile)END_MESSAGE_MAP()  // CChat 消息处理程序 void CChat::OnPaint(){    CPaintDC dc(this); // device context for painting    // TODO: 在此处添加消息处理程序代码    // 不为绘图消息调用 CDialog::OnPaint()     if( !m_imgBK.IsNull()) m_imgBK.Destroy();     m_imgBK.Load(_T("aio1.png"));    if( !m_imgBK.IsNull())         m_imgBK.Draw(dc.m_hDC, 0, 0, 540, 490);}    BOOL CChat::OnInitDialog(){    CDialog::OnInitDialog();     // TODO:  在此添加额外的初始化 ////////////////////////////////////////////////////////////////////////////////创建线程    m_socket=socket(AF_INET,SOCK_DGRAM,0);    if (INVALID_SOCKET==m_socket)    {        MessageBox(_T("套接字创建失败!"));        return FALSE;    } ////////////////////////////////////////////////////////////////////////////////数据库初始化     HRESULT hr;    hr=m_conPtr.CreateInstance(__uuidof(Connection));     if (SUCCEEDED(hr))    {         try        {            m_conPtr->Open(_bstr_t("provider=sqloledb.1; server=172.7.41.31\SQL2005; database=NetChat ")                  , _bstr_t("sa"), _bstr_t("123"), -1);             CString Sqlstr=_T("select *  from  NetChat");            m_rsPtr.CreateInstance(__uuidof(Recordset));            m_rsPtr->Open(_bstr_t(Sqlstr), m_conPtr.GetInterfacePtr(), adOpenKeyset, adLockPessimistic , adCmdText);            _RecordsetPtr TempPtr;            TempPtr=m_conPtr->Execute( _bstr_t(Sqlstr),NULL, adCmdText );         }        catch (_com_error e)        {            CString errMsg;            errMsg.Format(_T("连接错误,原因:%s"),e.ErrorMessage());            AfxMessageBox( errMsg);            return FALSE;        }     }      return TRUE;  // return TRUE unless you set the focus to a control    // 异常: OCX 属性页应返回 FALSE}  void CChat::OnBnClickedBtnEnter(){    // TODO: 在此添加控件通知处理程序代码         UpdateData( true);    if( m_Send.IsEmpty()){        AfxMessageBox("发送不允许为空!");        return;    }     CString strIP;    char szHostName[128];    if (gethostname(szHostName, 128)==0)    {        struct hostent * pHost;        int i;        pHost = gethostbyname(szHostName);        for (i=0; pHost !=NULL && pHost->h_addr_list[i]!= NULL; i++)        {             int j;            for (j=0; j<pHost->h_length; j++)            {                CString addr;                if (j>=0)                {                     addr.Format(_T("%u"), (unsigned int)((unsigned char*)pHost->h_addr_list[i])[j]);                                     strIP += addr;                    if (j!=pHost->h_length-1)                    {                        strIP += ".";                    }                 }            }        }    }     CString strName;    strName.Format(_T("select ClientName from NetChat where TempIP='%s'"), strIP);     _RecordsetPtr rsPtr;    rsPtr=m_conPtr->Execute(_bstr_t(strName), NULL, adCmdText);    CString strName1=rsPtr->GetCollect(_variant_t((long)0));     CString strTemp;        m_Recv.Format(_T("%s:%s"), strName1, m_Send);    m_Recv +="rn";    GetDlgItemText(IDC_EDIT_RECV,strTemp);    m_Recv +=strTemp;    SetDlgItemText(IDC_EDIT_RECV,m_Recv);      //////////////////////////////////////////////////////////////////////////////////////      CString buff;    SOCKADDR_IN AddrSvr;    AddrSvr.sin_family=AF_INET;    AddrSvr.sin_port=htons(3000);    AddrSvr.sin_addr.S_un.S_addr=inet_addr(m_RecvIP);       //绑定聊天对象服务器       char sendbuf[1024];    memset(sendbuf, 0, 1024);    strcpy(sendbuf, m_Send.GetBuffer(m_Send.GetLength()));    sendto(m_socket, sendbuf, 1024, 0, (SOCKADDR*)&AddrSvr, sizeof(SOCKADDR));         m_Send.Empty();    UpdateData(false);  }  //接收聊天对象IP地址和端口LRESULT CChat::OnRecvIP(WPARAM wParam, LPARAM lParam){    m_RecvIP.Format(_T("%s"), (char*)lParam);         return LRESULT();}    LRESULT CChat::OnRecvShow(WPARAM wParam, LPARAM lParam){     m_RecvStr=*((CString *)lParam);    CString strIP=*((CString *)wParam);    CString str;    str.Format(_T("select ClientName from NetChat where TempIP='%s'"), strIP);    m_rsPtr=m_conPtr->Execute(_bstr_t(str), NULL, adCmdText);    CString str1=m_rsPtr->GetCollect(_variant_t((long)0));    str1 +=':';    str1 +=m_RecvStr;     m_RecvStr.Format(_T("%s"),str1);    CString strTemp;    GetDlgItemText(IDC_EDIT_RECV,strTemp);    m_RecvStr +="rn";    m_RecvStr +=strTemp;          GetDlgItem(IDC_EDIT_RECV)->SetWindowText(m_RecvStr);          return LRESULT();}  // Register.cpp : 实现文件// #include "stdafx.h"#include "MFCNetChat.h"#include "Register.h"  // CRegister 对话框 IMPLEMENT_DYNAMIC(CRegister, CDialog) CRegister::CRegister(CWnd* pParent /*=NULL*/)    : CDialog(CRegister::IDD, pParent)    , m_RegisterName(_T(""))    , m_RegisterPwd1(_T(""))    , m_RegisterPwd2(_T(""))    , m_RegisterQues(_T(""))    , m_RegisterAnsw(_T(""))     { } CRegister::~CRegister(){} void CRegister::DoDataExchange(CDataExchange* pDX){    CDialog::DoDataExchange(pDX);    DDX_Text(pDX, IDC_REGI_NAME, m_RegisterName);    DDX_Text(pDX, IDC_REGI_PWD1, m_RegisterPwd1);    DDX_Text(pDX, IDC_REGI_PWD2, m_RegisterPwd2);    DDX_Text(pDX, IDC_REGI_QUESTION, m_RegisterQues);    DDX_Text(pDX, IDC_REGI_ANSWER, m_RegisterAnsw);}  BEGIN_MESSAGE_MAP(CRegister, CDialog)    ON_BN_CLICKED(IDC_REGISTER_OK, &CRegister::OnBnClickedRegisterOk)END_MESSAGE_MAP()  // CRegister 消息处理程序 BOOL CRegister::OnInitDialog(){    CDialog::OnInitDialog();     // TODO:  在此添加额外的初始化      HRESULT hr;    hr=m_conPtr.CreateInstance(__uuidof(Connection));     if (SUCCEEDED(hr))    {         try        {            m_conPtr->Open(_bstr_t("provider=sqloledb.1; server=172.7.41.31\SQL2005; database=NetChat ")                  , _bstr_t("sa"), _bstr_t("123"), -1);             CString Sqlstr=_T("select *  from  NetChat");            m_rsPtr.CreateInstance(__uuidof(Recordset));            m_rsPtr->Open(_bstr_t(Sqlstr), m_conPtr.GetInterfacePtr(), adOpenKeyset, adLockPessimistic , adCmdText);            _RecordsetPtr TempPtr;            TempPtr=m_conPtr->Execute( _bstr_t(Sqlstr),NULL, adCmdText );         }        catch (_com_error e)        {            CString errMsg;            errMsg.Format(_T("连接错误,原因:%s"),e.ErrorMessage());            AfxMessageBox( errMsg);            return FALSE;        }     }      return TRUE;  // return TRUE unless you set the focus to a control    // 异常: OCX 属性页应返回 FALSE}   void CRegister::OnBnClickedRegisterOk(){    // TODO: 在此添加控件通知处理程序代码     try{         UpdateData(true);        if (m_RegisterPwd1.Compare(m_RegisterPwd2))        {            AfxMessageBox(_T("您两次输入的密码不同!"));            return;        }         CString RegisterStr;        RegisterStr.Format(_T("insert into NetChat(ClientName, ClientPwd, Question, Answer)                                values( '%s', '%s', '%s', '%s')"), m_RegisterName, m_RegisterPwd1                              , m_RegisterQues, m_RegisterAnsw );        m_conPtr->Execute(_bstr_t(RegisterStr), NULL, adCmdText);                 int nIndex;        CString RegisterStr1;        RegisterStr1.Format(_T("select Max(ClientID) from NetChat"));        _RecordsetPtr rsPtr;        rsPtr=m_conPtr->Execute(_bstr_t(RegisterStr1), NULL, adCmdText);        nIndex=rsPtr->GetCollect(_variant_t((long)0));        CString str;        str.Format(_T("恭喜您,注册成功!n  您的账号为: %d   n  请妥善保管!"), nIndex);         CString FriendList;          FriendList.Format(_T("create table %s(FriendNum bigint primary key(FriendNum) identity(1,1), FriendName nvarchar(50) not null)"), m_RegisterName);        m_rsPtr=m_conPtr->Execute(_bstr_t(FriendList), NULL, adCmdText);         AfxMessageBox(str);    }    catch(_com_error e){        AfxMessageBox(e.ErrorMessage());        return;    }        OnOK();}   // AddFriend.cpp : 实现文件// #include "stdafx.h"#include "MFCNetChat.h"#include "AddFriend.h"  // CAddFriend 对话框 IMPLEMENT_DYNAMIC(CAddFriend, CDialog) CAddFriend::CAddFriend(CWnd* pParent /*=NULL*/)    : CDialog(CAddFriend::IDD, pParent)    , m_AddFriend(0){ } CAddFriend::~CAddFriend(){} void CAddFriend::DoDataExchange(CDataExchange* pDX){    CDialog::DoDataExchange(pDX);    DDX_Text(pDX, IDC_EDIT1, m_AddFriend);    DDX_Control(pDX, IDC_LIST1, m_ListCtrl);}  BEGIN_MESSAGE_MAP(CAddFriend, CDialog)    ON_BN_CLICKED(IDC_ADD_SEARCH, &CAddFriend::OnBnClickedAddSearch)    ON_BN_CLICKED(IDC_ADD_ADD, &CAddFriend::OnBnClickedAddAdd)END_MESSAGE_MAP()  // CAddFriend 消息处理程序 void CAddFriend::OnBnClickedAddSearch(){    // TODO: 在此添加控件通知处理程序代码    UpdateData(true);    CString searchName;    CString searchIP;    CString str;    int nIndex = m_ListCtrl.GetItemCount();    for (int i=nIndex-1; i>=0; i-- )    {        if (nIndex!=0)        {            m_ListCtrl.DeleteItem(i);        }    } //此处可改为重名用户的多人结果列表--待修改     str.Format(_T("select ClientID, ClientName, Status from NetChat where ClientID=%d "), m_AddFriend);    m_rsPtr=m_conPtr->Execute(_bstr_t(str), NULL, adCmdText);         CString str1,str2,str3;    str3 =(CString)m_rsPtr->GetCollect(_variant_t((long)0));    str1 =(CString)m_rsPtr->GetCollect(_variant_t((long)1));    str2 =(CString)m_rsPtr->GetCollect(_variant_t((long)2));     m_ListCtrl.InsertItem(0, str3, 0);    m_ListCtrl.SetItemText(0, 1, str1);    m_ListCtrl.SetItemText(0, 2, str2); } BOOL CAddFriend::OnInitDialog(){    CDialog::OnInitDialog();     // TODO:  在此添加额外的初始化     HRESULT hr;    hr=m_conPtr.CreateInstance(__uuidof(Connection));     if (SUCCEEDED(hr))    {         try        {            m_conPtr->Open(_bstr_t("provider=sqloledb.1; server=172.7.41.31\SQL2005; database=NetChat ")                  , _bstr_t("sa"), _bstr_t("123"), -1);             CString Sqlstr=_T("select *  from  NetChat");            m_rsPtr.CreateInstance(__uuidof(Recordset));            m_rsPtr->Open(_bstr_t(Sqlstr), m_conPtr.GetInterfacePtr(), adOpenKeyset, adLockPessimistic , adCmdText);            _RecordsetPtr TempPtr;            TempPtr=m_conPtr->Execute( _bstr_t(Sqlstr),NULL, adCmdText );         }        catch (_com_error e)        {            CString errMsg;            errMsg.Format(_T("连接错误,原因:%s"),e.ErrorMessage());            AfxMessageBox( errMsg);            return FALSE;        }     }     m_ListCtrl.SetExtendedStyle(        m_ListCtrl.GetExtendedStyle()|LVS_EX_CHECKBOXES|LVS_EX_FULLROWSELECT|LVS_EX_GRIDLINES);     m_ListCtrl.InsertColumn( 0, _T("好友ID"), LVCFMT_LEFT, 80);    m_ListCtrl.InsertColumn( 1, _T("好友昵名"), LVCFMT_LEFT, 80);    m_ListCtrl.InsertColumn( 2, _T("好友状态"), LVCFMT_LEFT, 80);                    return TRUE;  // return TRUE unless you set the focus to a control    // 异常: OCX 属性页应返回 FALSE} void CAddFriend::OnBnClickedAddAdd(){    // TODO: 在此添加控件通知处理程序代码     int nIndex=m_ListCtrl.GetItemCount();    for (int i=0; i<nIndex; i++)    {        if (m_ListCtrl.GetCheck(i))        {            CWnd *wnd=GetParent();            ::SendMessage(wnd->m_hWnd, WM_ADDFRIEND, 0, (LPARAM)m_AddFriend);        }    }  }   // Forget.cpp : 实现文件// #include "stdafx.h"#include "MFCNetChat.h"#include "Forget.h"#include <atlimage.h>  // CForget 对话框 IMPLEMENT_DYNAMIC(CForget, CDialog) CForget::CForget(CWnd* pParent /*=NULL*/)    : CDialog(CForget::IDD, pParent)    , m_ForgetID(0)    , m_ForgetQues(_T(""))    , m_ForgetAnswer(_T(""))    , m_NewPwd1(_T(""))    , m_NewPwd2(_T("")){ } CForget::~CForget(){} void CForget::DoDataExchange(CDataExchange* pDX){    CDialog::DoDataExchange(pDX);    DDX_Text(pDX, IDC_FORGET_NAME, m_ForgetID);    DDX_Text(pDX, IDC_FORGET_QUETION, m_ForgetQues);    DDX_Text(pDX, IDC_FORGET_ANSWER, m_ForgetAnswer);    DDX_Text(pDX, IDC_FORGET_PWD1, m_NewPwd1);    DDX_Text(pDX, IDC_FORGET_PWD2, m_NewPwd2);}  BEGIN_MESSAGE_MAP(CForget, CDialog)    ON_BN_CLICKED(IDOK, &CForget::OnBnClickedOk)    ON_WM_PAINT()END_MESSAGE_MAP()  // CForget 消息处理程序 BOOL CForget::OnInitDialog(){    CDialog::OnInitDialog();     // TODO:  在此添加额外的初始化     HRESULT hr;    hr=m_conPtr.CreateInstance(__uuidof(Connection));     if (SUCCEEDED(hr))    {         try        {            m_conPtr->Open(_bstr_t("provider=sqloledb.1; server=172.7.41.31\SQL2005; database=NetChat ")                  , _bstr_t("sa"), _bstr_t("123"), -1);             CString Sqlstr=_T("select *  from  NetChat");            m_rsPtr.CreateInstance(__uuidof(Recordset));            m_rsPtr->Open(_bstr_t(Sqlstr), m_conPtr.GetInterfacePtr(), adOpenKeyset, adLockPessimistic , adCmdText);            _RecordsetPtr TempPtr;            TempPtr=m_conPtr->Execute( _bstr_t(Sqlstr),NULL, adCmdText );         }        catch (_com_error e)        {            CString errMsg;            errMsg.Format(_T("连接错误,原因:%s"),e.ErrorMessage());            AfxMessageBox( errMsg);            return FALSE;        }     }     return TRUE;  // return TRUE unless you set the focus to a control    // 异常: OCX 属性页应返回 FALSE} void CForget::OnBnClickedOk(){    // TODO: 在此添加控件通知处理程序代码    UpdateData(true);    CString searchStr;     searchStr.Format(_T("select count(ClientID) from NetChat where ClientID=%d and Question='%s'"), m_ForgetID, m_ForgetQues);    _RecordsetPtr TempPtr;    TempPtr=m_conPtr->Execute(_bstr_t(searchStr), NULL, adCmdText);    int nIndex=TempPtr->GetCollect(_variant_t((long)0));    if (nIndex==0)    {        AfxMessageBox(_T("对不起,您要找回的账号不存在 n  或密码问题不正确 !"));        return;    }else{        CString searchStr1;        searchStr1.Format(_T("select Answer from NetChat where ClientID=%d"), m_ForgetID);        _RecordsetPtr TempPtr1;        TempPtr1=m_conPtr->Execute(_bstr_t(searchStr1), NULL, adCmdText);        CString nIndex1=TempPtr1->GetCollect(_variant_t((long)0));        if (!nIndex1.Compare(m_ForgetAnswer))        {            if (m_NewPwd1.Compare(m_NewPwd2))            {                AfxMessageBox(_T("您2次修改的密码不同!"));                return;            }            m_rsPtr->PutCollect(_variant_t("ClientPwd"), _variant_t(m_NewPwd1));            m_rsPtr->Update();            AfxMessageBox(_T("密码修改成功!"));        }else{            AfxMessageBox(_T("对不起您的密码回答不正确!"));            return;        }    }          OnOK();} void CForget::OnPaint(){    CPaintDC dc(this); // device context for painting    // TODO: 在此处添加消息处理程序代码    // 不为绘图消息调用 CDialog::OnPaint()           if( !m_imgBK.IsNull()) m_imgBK.Destroy();     m_imgBK.Load(_T("aio.png"));    if( !m_imgBK.IsNull())         m_imgBK.Draw(dc.m_hDC, 0, 0, 512, 342);}    #include "stdafx.h"#include "resource.h"#include "CsplashWnd.h"     // CSplashWnd    //IMPLEMENT_DYNAMIC(CSplashWnd, CWnd)    BOOL CSplashWnd::c_bShowSplashWnd = FALSE;    CSplashWnd* CSplashWnd::c_pSplashWnd;    CSplashWnd::CSplashWnd()    {    }    CSplashWnd::~CSplashWnd()    {        // Clear the static window pointer.        ASSERT(c_pSplashWnd == this);        c_pSplashWnd = NULL;    }     BEGIN_MESSAGE_MAP(CSplashWnd, CWnd)        ON_WM_CREATE()        ON_WM_PAINT()        ON_WM_TIMER()    END_MESSAGE_MAP()     void CSplashWnd::EnableSplashScreen(BOOL bEnable )    {        c_bShowSplashWnd = bEnable;    }    void CSplashWnd::ShowSplashScreen(CWnd* pParentWnd )    {        if (!c_bShowSplashWnd || c_pSplashWnd != NULL)            return;        // Allocate a new splash screen, and create the window.        c_pSplashWnd = new CSplashWnd;        if (!c_pSplashWnd->Create(pParentWnd))            delete c_pSplashWnd;        else            c_pSplashWnd->UpdateWindow();    }    BOOL CSplashWnd::PreTranslateAppMessage(MSG* pMsg)    {        if (c_pSplashWnd == NULL)            return FALSE;        // If we get a keyboard or mouse message, hide the splash screen.        if (pMsg->message == WM_KEYDOWN ||            pMsg->message == WM_SYSKEYDOWN ||            pMsg->message == WM_LBUTTONDOWN ||            pMsg->message == WM_RBUTTONDOWN ||            pMsg->message == WM_MBUTTONDOWN ||            pMsg->message == WM_NCLBUTTONDOWN ||            pMsg->message == WM_NCRBUTTONDOWN ||            pMsg->message == WM_NCMBUTTONDOWN)        {            c_pSplashWnd->HideSplashScreen();            return TRUE; // message handled here        }        return FALSE; // message not handled    }    BOOL CSplashWnd::Create(CWnd* pParentWnd )    {        if (!m_bitmap.LoadBitmap(IDB_BITMAP3))            return FALSE;        BITMAP bm;        m_bitmap.GetBitmap(&bm);        return CreateEx(0,            AfxRegisterWndClass(0, AfxGetApp()->LoadStandardCursor(IDC_ARROW)),            NULL, WS_POPUP | WS_VISIBLE, 0, 0, bm.bmWidth, bm.bmHeight, pParentWnd->GetSafeHwnd(), NULL);    }     void CSplashWnd::HideSplashScreen()    {        // Destroy the window, and update the mainframe.        DestroyWindow();        AfxGetMainWnd()->UpdateWindow();    }    void CSplashWnd::PostNcDestroy()    {        // Free the C++ class.        delete this;    }    int CSplashWnd::OnCreate(LPCREATESTRUCT lpCreateStruct)    {        if (CWnd::OnCreate(lpCreateStruct) == -1)            return -1;        // Center the window.        CenterWindow();        // Set a timer to destroy the splash screen.        SetTimer(1, 1000, NULL);        return 0;    }    void CSplashWnd::OnPaint()    {        CPaintDC dc(this);        CDC dcImage;        if (!dcImage.CreateCompatibleDC(&dc))            return;        BITMAP bm;        m_bitmap.GetBitmap(&bm);        // Paint the image.        CBitmap* pOldBitmap = dcImage.SelectObject(&m_bitmap);        dc.BitBlt(0, 0, bm.bmWidth, bm.bmHeight, &dcImage, 0, 0, SRCCOPY);        dcImage.SelectObject(pOldBitmap);    }    void CSplashWnd::OnTimer(UINT nIDEvent)    {        // Destroy the splash screen window.        HideSplashScreen();    }

原创粉丝点击