MFC多线程查找文件

LRESULT C多线程查找文件Dlg::OnAddItemMessage(WPARAM wParam, LPARAM lParam){//LRESULT == long
        CString* str = (CString*)wParam;
        myList.InsertItem(0,*str);
        delete str;
return 0;
}

HANDLE semaphoreh;
//查找文件线程
UINT __cdecl MyThread( LPVOID pParam ){

    CMyFile* file = (CMyFile*)pParam;

    CString path = file->path;
    if(path[path.GetLength()-1]!='\\'){
        path+="\\";
    }
    CFileFind mFinder;
    CString str=path+_T("*.*");
    BOOL b = mFinder.FindFile(str);//如果查找到就返回TRUE

    while(b){
        b=mFinder.FindNextFileW();
        if(mFinder.IsDots()){//如果是.和..的话则返回继续遍历
            continue;
        }else if(mFinder.IsDirectory()){//如果是文件的话,则启动一个线程
            CMyFile* file1 = new CMyFile();
            file1->path = mFinder.GetFilePath();
            file1->name = file->name;
            file1->h = file->h;
            DWORD ret =  WaitForSingleObject(semaphoreh,5000);
            AfxBeginThread(MyThread,file1);
        }else{
            //说明找到的是文件
            //咱们就发送消息添加到列表框
            if(mFinder.GetFileName().Find(file->name) >0){
                CString* tempPath = new CString(file->path+mFinder.GetFileName());
                SendMessage(file->h, WM_AddItemMessage, (WPARAM)tempPath, NULL);//发送了
            }
        }
    }
    ReleaseSemaphore(semaphoreh,1,NULL);
    delete file;
return 0;
}
void C多线程查找文件Dlg::OnBnClickedButton1()
{
    semaphoreh = CreateSemaphore(NULL,20,20,NULL);//因为只在我们这个线程使用,所以就不需要名字,
    CMyFile* file = new CMyFile();
    GetDlgItemText(IDC_EDIT1,file->path);
    GetDlgItemText(IDC_EDIT2,file->name);
    file->h = this->m_hWnd;
    AfxBeginThread(MyThread,file);
}

 

posted @ 2013-08-04 01:06  宝贝,我永远都在  阅读(300)  评论(0)    收藏  举报