BOOL CRadiantApp::InitInstance() { //g_hOpenGL32 = ::LoadLibrary("opengl32.dll"); // AfxEnableControlContainer(); // Standard initialization // If you are not using these features and wish to reduce the size // of your final executable, you should remove from the following // the specific initialization routines you do not need. //AfxEnableMemoryTracking(FALSE); #ifdef _AFXDLL //Enable3dControls(); // Call this when using MFC in a shared DLL #else //Enable3dControlsStatic(); // Call this when linking to MFC statically #endif // If there's a .INI file in the directory use it instead of registry char RadiantPath[_MAX_PATH]; GetModuleFileName( NULL, RadiantPath, _MAX_PATH ); // search for exe CFileFind Finder; Finder.FindFile( RadiantPath ); Finder.FindNextFile(); // extract root CString Root = Finder.GetRoot(); // build root\*.ini CString IniPath = Root + "\\REGISTRY.INI"; // search for ini file Finder.FindNextFile(); if( Finder.FindFile( IniPath ) ) { Finder.FindNextFile(); // use the .ini file instead of the registry free( ( void * )m_pszProfileName ); m_pszProfileName = _tcsdup( _T( Finder.GetFilePath() ) ); // look for the registry key for void* buffers storage ( these can't go into .INI files ) int i = 0; CString key; HKEY hkResult; DWORD dwDisp; DWORD type; char iBuf[3]; do { sprintf( iBuf, "%d", i ); key = "Software\\Q3Radiant\\IniPrefs" + CString( iBuf ); // does this key exists ? if( RegOpenKeyEx( HKEY_CURRENT_USER, key, 0, KEY_ALL_ACCESS, &hkResult ) != ERROR_SUCCESS ) { // this key doesn't exist, so it's the one we'll use strcpy( g_qeglobals.use_ini_registry, key.GetBuffer( 0 ) ); RegCreateKeyEx( HKEY_CURRENT_USER, key, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hkResult, &dwDisp ); RegSetValueEx( hkResult, "RadiantName", 0, REG_SZ, reinterpret_cast<CONST BYTE *>( RadiantPath ), strlen( RadiantPath ) + 1 ); RegCloseKey( hkResult ); break; } else { char RadiantAux[ _MAX_PATH ]; unsigned long size = _MAX_PATH; // the key exists, is it the one we are looking for ? RegQueryValueEx( hkResult, "RadiantName", 0, &type, reinterpret_cast<BYTE *>( RadiantAux ), &size ); RegCloseKey( hkResult ); if( !strcmp( RadiantAux, RadiantPath ) ) { // got it ! strcpy( g_qeglobals.use_ini_registry, key.GetBuffer( 0 ) ); break; } } i++; } while( 1 ); g_qeglobals.use_ini = true; } else { // Change the registry key under which our settings are stored. SetRegistryKey( EDITOR_REGISTRY_KEY ); g_qeglobals.use_ini = false; } LoadStdProfileSettings(); // Load standard INI file options (including MRU) // Register the application's document templates. Document templates // serve as the connection between documents, frame windows and views. // CMultiDocTemplate* pDocTemplate; // pDocTemplate = new CMultiDocTemplate( // IDR_RADIANTYPE, // RUNTIME_CLASS(CRadiantDoc), // RUNTIME_CLASS(CMainFrame), // custom MDI child frame // RUNTIME_CLASS(CRadiantView)); // AddDocTemplate(pDocTemplate); // create main MDI Frame window g_PrefsDlg.LoadPrefs(); glEnableClientState( GL_VERTEX_ARRAY ); CString strTemp = m_lpCmdLine; strTemp.MakeLower(); if( strTemp.Find( "builddefs" ) >= 0 ) { g_bBuildList = true; } CMainFrame *pMainFrame = new CMainFrame; if( !pMainFrame->LoadFrame( IDR_MENU_QUAKE3 ) ) { return FALSE; } if( pMainFrame->m_hAccelTable ) { ::DestroyAcceleratorTable( pMainFrame->m_hAccelTable ); } pMainFrame->LoadAccelTable( MAKEINTRESOURCE( IDR_MINIACCEL ) ); m_pMainWnd = pMainFrame; // The main window has been initialized, so show and update it. pMainFrame->ShowWindow( m_nCmdShow ); pMainFrame->UpdateWindow(); return TRUE; }
void CBATCHDlg::OnBnClickedButtonSeletepath() { TCHAR szFolderPath[MAX_PATH] = {0}; CString strFolderPath = TEXT(""); BROWSEINFO sInfo; ::ZeroMemory(&sInfo, sizeof(BROWSEINFO)); sInfo.pidlRoot = 0; sInfo.lpszTitle = _T("ÇëÑ¡ÔñÒ»¸öÎļþ¼Ð£º"); sInfo.ulFlags = BIF_DONTGOBELOWDOMAIN | BIF_RETURNONLYFSDIRS | BIF_NEWDIALOGSTYLE | BIF_EDITBOX; sInfo.lpfn = NULL; // ÏÔʾÎļþ¼ÐÑ¡Ôñ¶Ô»°¿ò LPITEMIDLIST lpidlBrowse = ::SHBrowseForFolder(&sInfo); if (lpidlBrowse != NULL) { // È¡µÃÎļþ¼ÐÃû if (::SHGetPathFromIDList(lpidlBrowse,szFolderPath)) { strFolderPath = szFolderPath; m_path = strFolderPath; CString str_file = strFolderPath; CString res_str; m_images.clear(); CString suffixs[] = {"\\*.jpg","\\*.jpeg","\\*.bmp","\\*.png"}; for(int i = 0; i < 4; ++i) { CFileFind finder; CString filepathname; BOOL YesNo=finder.FindFile(str_file + suffixs[i]); while (YesNo) { YesNo=finder.FindNextFile(); filepathname=finder.GetFilePath(); m_images.push_back(filepathname); } } for(vector<CString>::size_type v_i = 0; v_i != m_images.size(); ++v_i) { res_str += m_images[v_i]; res_str += "\r\n"; } m_res = res_str; UpdateData(FALSE); } } if(lpidlBrowse != NULL) { ::CoTaskMemFree(lpidlBrowse); } }
BOOL CDlgNote::OnInitDialog() { CDialogEx::OnInitDialog(); // TODO: 在此添加额外的初始化 ///SetWindowPos(NULL, 0+1, CAPTIONHEIGHT+TOOLHEIGHT+1, MINSIZEX-2, MINSIZEY-(CAPTIONHEIGHT+TOOLHEIGHT)-2, NULL);//left top width height SetWindowPos(NULL, 0+1, CAPTIONHEIGHT+TOOLHEIGHT+1, MINSIZEX-2, MINSIZEY-(CAPTIONHEIGHT+TOOLHEIGHT)-2, NULL); //SetBackgroundColor(RGB(45,62,92),TRUE); SetBackgroundColor(RGB(105,161,191),TRUE); m_List_ctlTitle.SetBkColor(LISTCONTROLBACKGROUNDCOLOR); m_List_ctlTitle.SetRowHeigt(25); //设置行高度 m_List_ctlTitle.SetHeaderHeight(1); //设置头部高度 m_List_ctlTitle.SetHeaderFontHW(12,0); //设置头部字体高度,和宽度,0表示缺省,自适应 m_List_ctlTitle.SetHeaderTextColor(RGB(105,161,191)); //设置头部字体颜色 m_List_ctlTitle.SetHeaderBKColor(76,85,89,1); //设置头部背景色 m_List_ctlTitle.SetFontHW(12,0); //设置字体高度,和宽度,0表示缺省宽度 m_List_ctlTitle.SetColTextColor(0,RGB(255,255,255)); //设置列文本颜色 m_List_ctlTitle.InsertColumn(0,_T("备忘标题"),LVCFMT_LEFT,80); m_List_ctlTitle.InsertColumn(1,_T("文件路径"),LVCFMT_LEFT,0); m_List_ctlTitle.MoveWindow(1,0,168,550+27); CRect rcClient; m_List_ctlTitle.GetClientRect(&rcClient); m_List_ctlTitle.SetColumnWidth(0,rcClient.Width()); m_Button_ctlNew.LoadStdImage(IDB_PNG_NEW, _T("PNG")); m_Button_ctlNew.MoveWindow(169,1,63,24,TRUE);//62,23 m_Button_ctlSave.LoadStdImage(IDB_PNG_NOTESAVE, _T("PNG")); m_Button_ctlSave.MoveWindow(MINSIZEX-63*2-5-20,1,63,24,TRUE); m_Button_ctlCancel.LoadStdImage(IDB_PNG_NOTEDEL, _T("PNG")); m_Button_ctlCancel.MoveWindow(MINSIZEX-63-20,1,63,24,TRUE); // CRect rcClient; m_List_ctlTitle.GetClientRect(&rcClient); m_List_ctlTitle.SetColumnWidth(0,rcClient.Width()); m_Edit_ctlTitle.MoveWindow(168,25,MINSIZEX-2-168,25); m_Edit_ctlContent.MoveWindow(168,51,MINSIZEX-2-168,MINSIZEY-(CAPTIONHEIGHT+TOOLHEIGHT)-2-23-2-25-4); int i=0; CFileFind finder; CString strPath; CString strFileName; CString strSavePath; strSavePath=CBoBoDingApp::g_strNotePath+_T("*.txt"); BOOL bWorking = finder.FindFile(strSavePath); while (bWorking) { bWorking = finder.FindNextFile(); strPath=finder.GetFilePath(); strFileName=finder.GetFileTitle(); //strPath就是所要获取Test目录下的文件夹和文件(包括路径) m_List_ctlTitle.InsertItem(i,strFileName,LVCFMT_LEFT); m_List_ctlTitle.SetItemText(i,1,strPath); i++; } m_Font.CreatePointFont(105, _T("宋体")); m_Edit_ctlTitle.SetFont(&m_Font); m_Edit_ctlContent.SetFont(&m_Font); m_List_ctlTitle.EnableScrollBar(SB_HORZ, ESB_DISABLE_BOTH); /******************************************************************************/ //m_Button_ctlSave.EnableButton(FALSE); //m_Button_ctlCancel.EnableButton(FALSE); return TRUE; // return TRUE unless you set the focus to a control // 异常: OCX 属性页应返回 FALSE }
void ListFileProvider::fillFiles( const CString& path ) { CFileFind finder; CString p = path + "\\*.*"; if ( !finder.FindFile( p ) ) return; // hack to avoid reading std::string legacyThumbnailPostfix = ".thumbnail.bmp"; int legacyThumbSize = (int)legacyThumbnailPostfix.length(); int thumbSize = (int)thumbnailPostfix_.length(); bool ignoreFiles = false; if ( !includeFolders_.empty() && !StringUtils::matchSpec( (LPCTSTR)path, includeFolders_ ) ) ignoreFiles = true; BOOL notEOF = TRUE; while( notEOF && getThreadWorking() ) { notEOF = finder.FindNextFile(); if ( !finder.IsDirectory() ) { if ( !ignoreFiles ) { std::string fname( (LPCTSTR)finder.GetFileName() ); if ( StringUtils::matchExtension( fname, extensions_ ) && ( (int)fname.length() <= thumbSize || fname.substr( fname.length() - thumbSize ) != thumbnailPostfix_ ) && ( (int)fname.length() <= legacyThumbSize || fname.substr( fname.length() - legacyThumbSize ) != legacyThumbnailPostfix ) ) { ListItemPtr item = new ListItem(); item->fileName = (LPCTSTR)finder.GetFilePath(); item->dissolved = BWResource::dissolveFilename( item->fileName ); item->title = (LPCTSTR)finder.GetFileName(); threadMutex_.grab(); if ( (threadItems_.size() % VECTOR_BLOCK_SIZE) == 0 ) threadItems_.reserve( threadItems_.size() + VECTOR_BLOCK_SIZE ); threadItems_.push_back( item ); threadMutex_.give(); } } } else if ( !finder.IsDots() && !( flags_ & LISTFILEPROV_DONTRECURSE ) && ( excludeFolders_.empty() || !StringUtils::matchSpec( (LPCTSTR)finder.GetFilePath(), excludeFolders_ ) ) ) { fillFiles( finder.GetFilePath() ); } if ( threadYieldMsec_ > 0 ) { if ( ( clock() - yieldClock_ ) * 1000 / CLOCKS_PER_SEC > threadYieldMsec_ ) { Sleep( 50 ); // yield yieldClock_ = clock(); } } if ( ( clock() - flushClock_ ) * 1000 / CLOCKS_PER_SEC >= threadFlushMsec_ ) { flushThreadBuf(); flushClock_ = clock(); } } }
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[]) { int nRetCode = 0; HMODULE hModule = ::GetModuleHandle(NULL); if (hModule != NULL) { // 初始化 MFC 并在失败时显示错误 if (!AfxWinInit(hModule, NULL, ::GetCommandLine(), 0)) { // TODO: 更改错误代码以符合您的需要 _tprintf(_T("错误: MFC 初始化失败\n")); nRetCode = 1; } else { // TODO: 在此处为应用程序的行为编写代码。 char m_ExePath[256]; GetModuleFileName(NULL, m_ExePath, 256); CString localpath; localpath = m_ExePath; int nLength = localpath.ReverseFind('\\'); localpath = localpath.Left(nLength+1); CString configPath = localpath + "config.ini"; // ready char inputPath[1000]; CString srcPath ; CString dstPath ; memset(inputPath, '\0', 1000); GetPrivateProfileString("PATH", "srcPath", "", inputPath, sizeof(inputPath), configPath); srcPath = inputPath; printf("srcPath %s\n", inputPath); GetPrivateProfileString("PATH", "dstPath", "", inputPath, sizeof(inputPath), configPath); dstPath = inputPath; printf("dstPath %s\n", inputPath); int nLen = srcPath.GetLength(); char ch = srcPath.GetAt(nLen-1); if ( ch != '\\' ) srcPath += "\\"; nLen = dstPath.GetLength(); ch = dstPath.GetAt(nLen-1); if ( ch != '\\' ) dstPath += "\\"; vector<CString> imgSet; // Batch CFileFind mFinder; CString mFilePathName; CString mFileName; CString strImgPath; CString lastChars; while (1) { int mMorefiles = mFinder.FindFile(srcPath + "*"); if ( mMorefiles == 0 ) { AfxMessageBox("没有找到文件"); return 0; } AeiParser classBW; //classBW.getIniPath((string)srcPath, (string)dstPath); while ( mMorefiles ) { mMorefiles = mFinder.FindNextFile(); mFilePathName = mFinder.GetFilePath(); if ( mFilePathName == "" ) continue; if ( mFinder.IsDots() ) continue; mFileName = mFilePathName.Mid(mFilePathName.ReverseFind('\\') + 1); bool blFile = classBW.isValid((string)mFileName); if ( !blFile ) continue; CString mDstName = dstPath + mFileName; bool blRtnVal = classBW.ParseFrom((string)mFilePathName); if (!blRtnVal) { printf("ParseFrom Failed!\n"); } // blRtnVal = classBW.SaveTo((string)mDstName); // if (!blRtnVal) // { // printf("SaveTo Failed!\n"); // } string tmpVal; printf("main\n"); for (int kk = 0; kk < 7; kk++) { blRtnVal = classBW.SetValue("hxd1234", 18, 0, kk); if (!blRtnVal) { printf("SaveTo Failed!\n"); } //printf("idx= %d, %s\n", kk, tmpVal.c_str()); } blRtnVal = classBW.SaveTo((string)mDstName); if (!blRtnVal) { printf("SaveTo Failed!\n"); } continue; } } } } else { // TODO: 更改错误代码以符合您的需要 _tprintf(_T("错误: GetModuleHandle 失败\n")); nRetCode = 1; } return nRetCode; }
LRESULT CIMoteTerminal::OnReceiveSerialData(WPARAM wParam, LPARAM lParam) { //following couple of lines allow us to debug a raw datastream char *rxstring = (char *)lParam; DWORD numBytesReceived = (DWORD) wParam; BufferAppend(rxstring, numBytesReceived); delete []rxstring; return TRUE; #if 0 DWORD i,offset; //TRACE("Rx...Buffer = %#X\tNumBytesReceived = %d\n",rxstring,numBytesReceived); /***** data format for the accelerometer data looks something like: 0{2 bit addr}{5 data bits} {1}{7 data bits} ******/ for(offset=0; offset<numBytesReceived; offset++) { //find the correct first bytes if((rxstring[offset] & 0xE0) == 0) { break; } } //offset current points to the correct first element for us to look at //start reconstructing the 16 bit numbers and doing the divide for(i=offset;(i+6)<numBytesReceived; i+=6) { static bool init = false; POINT point; DWORD B,C,D,Tx, Ty,T; int Rx, Ry; B = ((rxstring[i] & 0x1F)<<7) | (rxstring[i+1] & 0x7F); C = ((rxstring[i+2] & 0x1F)<<7) | (rxstring[i+3] & 0x7F); D = ((rxstring[i+4] & 0x1F)<<7) | (rxstring[i+5] & 0x7F); Tx = B; Ty = D-C; T = C/2 + D/2 - B/2; Rx = ((Tx << 16) / T) - (65536/2); Ry = ((Ty << 16) / T) - (65536/2); //point.x =(LONG)( (rxstring[byte_index]<<8) + rxstring[byte_index+1]) -(65536/2); //point.x = (LONG)( (rxstring[byte_index]<<8) + rxstring[byte_index+1]); //TRACE("%d %d = %d\n",rxstring[i], rxstring[i+1], point.x); //TRACE("Found T, index %d \n", byte_index); //TRACE("Tx = %d, Ty = %d, T = %d, Rx = %d, Ry = %d\n",Tx, Ty, T, Rx, Ry); point.x = (LONG) Rx; point.y = (LONG) Ry; if(!init) { CIMoteCartesianPlot *pFrame=CreateNewView(0,0xDEADBEEF,0); pFrame->SetMappingFunction(-2,2); init = true; } AddPoint(point, 0); } delete rxstring; return TRUE; //#endif; POINT point; static bool bGotBeef = 0; static bool bFirstTime = true; static unsigned short NumDataBytes; static unsigned short NumBytesProcessed; //static int MoteIDs[NUMCHANNELS]; static unsigned short SensorID; static unsigned int MoteID; static unsigned int SensorType; static unsigned int ExtraInfo; static unsigned int TimeID; static unsigned int ChannelID; static unsigned char HeaderIndex; static unsigned char Header[16]; unsigned short *short_ptr; unsigned int *int_ptr; DWORD byte_index; static unsigned char LastByte = 0; // unsigned int ProblemIndex; unsigned int EmptyChannel; static unsigned int NumProblems = 0; CString logentry; static bool bPrintheader=true; CTime time; static int Tx, Ty, T, Rx, Ry, Tb, Tc, Td, b0, b1; static int CurrentCounter, CurrentByte; // Hack, for now statically allocate static unsigned char *CameraBuffer; static unsigned int CurrentCameraID; static unsigned int CameraBufferIndex; static unsigned int SegmentIndex; static bool PictureInProgress; static unsigned int LastPicID; #define MAX_PIC_SIZE 80000 #define INVALID_SENSOR 0 #define PH_SENSOR 1 #define PRESSURE_SENSOR 2 #define ACCELEROMETER_SENSOR 3 #define CAMERA_SENSOR 4 #define FIRST_SEGMENT 0x1111 #define MID_SEGMENT 0 #define END_OF_PIC 0xffff for(int channel = 0; (channel < NUMCHANNELS) && bFirstTime; channel++) { MoteIDs[channel] = 0; HeaderIndex = 0; CurrentCameraID = 0; CameraBuffer = NULL; CameraBufferIndex = 0; PictureInProgress = false; } if (bFirstTime) { // Figure out the start of the file names CFileFind finder; CString TempName; unsigned int TempID; LastPicID = 0; BOOL bResult = finder.FindFile("c:\\icam\\*.jpg"); while (bResult) { bResult = finder.FindNextFile(); TempName = finder.GetFileName(); if (sscanf((LPCSTR)TempName, "%d.jpg", &TempID) == 1) { // valid pic id if (LastPicID < TempID) { LastPicID = TempID; } } } LastPicID++; } bFirstTime = false; TRACE("Rx...Buffer = %#X\tNumBytesReceived = %d\n",rxstring,numBytesReceived); byte_index = 0; while(byte_index < numBytesReceived) { // Look for DEADBEEF, get all header info for(; (byte_index < numBytesReceived) && !bGotBeef; byte_index++) { switch (HeaderIndex) { case 0: if (rxstring[byte_index] == 0xEF) { HeaderIndex = 1; } break; case 1: if (rxstring[byte_index] == 0xBE) { HeaderIndex = 2; } else { HeaderIndex = 0; } break; case 2: if (rxstring[byte_index] == 0xAD) { HeaderIndex = 3; } else { HeaderIndex = 0; } break; case 3: if (rxstring[byte_index] == 0xDE) { HeaderIndex = 4; } else { HeaderIndex = 0; } break; case 13: // Done with header CurrentCounter = 0; CurrentByte = 0; bGotBeef = 1; Header[HeaderIndex] = rxstring[byte_index]; /* * Header : * DEADBEEF (4B) * MOTE ID (4B) * Sensor TYPE (2B) * LENGTH (2B) * Extra Info (2B) * */ int_ptr = (unsigned int *) &(Header[4]); MoteID = *int_ptr; short_ptr = (unsigned short *) &(Header[8]); SensorType = *short_ptr; short_ptr++; NumDataBytes = *short_ptr; short_ptr++; ExtraInfo = *short_ptr; NumBytesProcessed = 0; ChannelID = NUMCHANNELS; EmptyChannel = NUMCHANNELS; if (SensorType == CAMERA_SENSOR) { // check with segment TRACE("Camera seg %x, buf Index %d, NumDataBytes %d\r\n", ExtraInfo, CameraBufferIndex, NumDataBytes); if (ExtraInfo == FIRST_SEGMENT) { // first segment CurrentCameraID = MoteID; CameraBufferIndex = 0; if (!PictureInProgress) { // create buffer CameraBuffer = new unsigned char[MAX_PIC_SIZE]; PictureInProgress = true; } } SegmentIndex = 0; // Per segment index break; // don't process the channel stuff } // Find mote channel, for(int channel = 0; channel < NUMCHANNELS; channel++) { if (MoteIDs[channel] == MoteID) { ChannelID = channel; break; } else { if (MoteIDs[channel] == 0) { EmptyChannel = channel; } } } if (ChannelID == NUMCHANNELS) { // Didn't find a channel if (EmptyChannel < NUMCHANNELS) { // assign the mote id to this channel MoteIDs[EmptyChannel] = MoteID; ChannelID = EmptyChannel; CIMoteCartesianPlot *pFrame=CreateNewView(ChannelID,MoteID,SensorID); /* Note to LAMA: below is an example of how to use the setmapping function pFrame->SetMappingFunction(slope, offset, minrange, maxrange */ switch(SensorType) { case PH_SENSOR: pFrame->SetMappingFunction(0,14); rawdata = false; break; case PRESSURE_SENSOR: pFrame->SetMappingFunction(0,20.684); //pFrame->SetMappingFunction(0,300); rawdata = false; break; case ACCELEROMETER_SENSOR: pFrame->SetMappingFunction(-2,2); rawdata = false; break; default : //pFrame->SetMappingFunction(1,1,0,14); pFrame->SetMappingFunction(-32768,32768); } //UpdateAllViews(NULL); } /* * NOTE: if ChannelID is not assigned, * the processing will remain the same, but the data won't * be displayed. * TODO : handle later */ } //log transaction info to file here: if(bPrintheader) { logentry.Format("Timestamp, iMoteID, # of Bytes\r\n"); //logfile<<logentry<<endl; SaveLogEntry(&logentry); bPrintheader=false; } time=time.GetCurrentTime(); //logfile<<time.Format("%c"); SaveLogEntry(&time.Format("%c")); logentry.Format(", %#X, %d\r\n",MoteID, NumDataBytes); //logfile<<logentry<<endl; SaveLogEntry(&logentry); break; default: Header[HeaderIndex] = rxstring[byte_index]; HeaderIndex++; break; } } if (!bGotBeef) { delete []rxstring; return TRUE; } // Got DEADBEEF, process data for(; byte_index <numBytesReceived; byte_index++,NumBytesProcessed ++) { if (NumBytesProcessed >= NumDataBytes) { // go back to start, look for DEADBEEF again bGotBeef = false; HeaderIndex = 0; TRACE("Mote ID %lx, NumBytes %ld, byte index %d \n", MoteID, NumDataBytes, byte_index); //MoteID = 0; //NumDataBytes = 0; break; } if (rawdata) { //RAW_BYTES mode, no processing // Assume data is 2 bytes long, and back to back if (CurrentByte == 0) { b0 = rxstring[byte_index]; CurrentByte = 1; } else { b1 = rxstring[byte_index]; CurrentByte = 0; int sample_data; sample_data = (b1 <<8) + b0; //sample_data -= 0x2000; //sample_data = sample_data << 2; point.x = (LONG) sample_data; point.y = 0; //TRACE("sample is %d\r\n", sample_data); if (ChannelID < NUMCHANNELS) { // valid channel AddPoint(point, ChannelID); } } } else { if (CurrentByte == 0) { b0 = rxstring[byte_index]; CurrentByte = 1; if (SensorType == CAMERA_SENSOR) { // just copy data CameraBuffer[CameraBufferIndex] = b0; SegmentIndex++; CameraBufferIndex++; } } else { b1 = rxstring[byte_index]; CurrentByte = 0; switch(SensorType) { case PH_SENSOR: /* * A/D maps 0-5V range to 0-32 K * pH = -7.752 * V + 16.237 * V = raw_data * 5 / 32768 * The plot output expects the 0 - 14 range to be represented in -32 - 32 K * point.x = (-7.752 * (raw_data * 5/32768) + 16.237) * 64K / 14 - 32K */ double ph_data; ph_data = (b1 <<8) + b0; ph_data = -7.752 * (ph_data/ 32768) * 5 + 16.237; ph_data = (ph_data * 65536 / 14) - 32768; point.x = (LONG) ph_data; point.y = 0; if (ChannelID < NUMCHANNELS) { // valid channel AddPoint(point, ChannelID); } break; case PRESSURE_SENSOR: /* * A/D maps 0-5V range to 0-32 K * The plot output expects the 0 - 20.684 range to be represented in -32 - 32 K * point.x = (raw_data * 5/32768) * 64K / 20.684 - 32K */ int pressure_data; pressure_data = (b1 <<8) + b0; pressure_data = pressure_data * 2 - 32768; point.x = (LONG) pressure_data; point.y = 0; if (ChannelID < NUMCHANNELS) { // valid channel AddPoint(point, ChannelID); } break; case ACCELEROMETER_SENSOR: // TRACE("CurrentCounter %d, ByteIndex %d \n", CurrentCounter, byte_index); switch (CurrentCounter) { case 0: Tx = (b0 <<8) + b1;; CurrentCounter = 1; //TRACE("Found Tx, index %d \n", byte_index); break; case 1: Ty = (b0 <<8) + b1; CurrentCounter = 2; //TRACE("Found Ty, index %d \n", byte_index); break; case 2: T = (b0 <<8) + b1; Rx = ((Tx << 16) / T) - (65536/2); Ry = ((Ty << 16) / T) - (65536/2); //point.x =(LONG)( (rxstring[byte_index]<<8) + rxstring[byte_index+1]) -(65536/2); //point.x = (LONG)( (rxstring[byte_index]<<8) + rxstring[byte_index+1]); //TRACE("%d %d = %d\n",rxstring[i], rxstring[i+1], point.x); //TRACE("Found T, index %d \n", byte_index); //TRACE("Tx = %d, Ty = %d, T = %d, Rx = %d, Ry = %d\n",Tx, Ty, T, Rx, Ry); point.x = (LONG) Rx; point.y = (LONG) Ry; if (ChannelID < NUMCHANNELS) { // valid channel AddPoint(point, ChannelID); } CurrentCounter = 0; break; default: break; } break; case CAMERA_SENSOR: // just copy data CameraBuffer[CameraBufferIndex] = b1; SegmentIndex++; CameraBufferIndex++; break; } } //for now, just save the point in the x field of the structure } //NumBytesProcessed += 2; } TRACE("NumBytesProcessed %d, NumDataBytes %d\r\n", NumBytesProcessed, NumDataBytes); // Check if we reached the end of a picture, write it to file if ((SensorType == CAMERA_SENSOR) && (NumBytesProcessed == NumDataBytes) && (ExtraInfo == END_OF_PIC)) { // Create output buffer , assume header < 1000 unsigned char *JpgImage; int JpgImageLen; JpgImage = new unsigned char[CameraBufferIndex+1000]; // build jpeg image BuildJPG(CameraBuffer, CameraBufferIndex, JpgImage, &JpgImageLen); // write to file char pszFileName[200]; CFile PictureFile; CFileException fileException; sprintf(pszFileName, "c:\\icam\\%d.jpg", LastPicID); LastPicID++; if ( !PictureFile.Open( pszFileName, CFile::modeCreate | CFile::modeWrite | CFile::typeBinary, &fileException ) ) { TRACE( "Can't open file %s, error = %u\n", pszFileName, fileException.m_cause ); } //PictureFile.Write(CameraBuffer, CameraBufferIndex); PictureFile.Write(JpgImage, JpgImageLen); PictureFile.Close(); TRACE("Wrote Jpeg image raw %d\r\n", CameraBufferIndex); delete []CameraBuffer; delete []JpgImage; PictureInProgress = false; } } delete []rxstring; return TRUE; #endif; }
void CACEdit::ReadDirectory(CString m_Dir) { CFileFind FoundFiles; TCHAR ch; CWaitCursor hg; // Wenn mittem im Pfad, // vorheriges Verzeichnis einlesen. if (m_Dir.Right(1) != _T('\\')) { _tsplitpath(m_Dir, m_szDrive, m_szDir, m_szFname, m_szExt); m_Dir.Format(_T("%s%s"),m_szDrive, m_szDir); } //ist hübscher ch = (TCHAR)towupper(m_Dir.GetAt(0)); m_Dir.SetAt(0,ch); CString m_Name,m_File,m_Dir1 = m_Dir; if (m_Dir.Right(1) != _T('\\')) m_Dir += _T("\\"); if(m_LastDirectory.CompareNoCase(m_Dir) == 0 && m_Liste.m_SearchList.GetSize()) return; m_LastDirectory = m_Dir; m_Dir += _T("*.*"); BOOL bContinue = FoundFiles.FindFile(m_Dir); if(bContinue) RemoveSearchAll(); while (bContinue == TRUE) { bContinue = FoundFiles.FindNextFile(); m_File = FoundFiles.GetFileName(); if(FoundFiles.IsHidden() || FoundFiles.IsSystem()) continue; if(FoundFiles.IsDirectory()) { if(m_iMode & _MODE_ONLY_FILES) continue; if(FoundFiles.IsDots()) continue; if (m_File.Right(1) != _T('\\')) m_File += _T("\\"); } if(!FoundFiles.IsDirectory()) if(m_iMode & _MODE_ONLY_DIRS) continue; if(m_iMode & _MODE_FS_START_DIR_) { m_Name = m_File; } else { m_Name = m_Dir1; if (m_Name.Right(1) != _T('\\')) m_Name += _T("\\"); m_Name += m_File; } AddSearchString(m_Name); } FoundFiles.Close(); return; }
void InformApp::FindExtensions(void) { m_extensions.clear(); for (int i = 0; i < 2; i++) { CString path; switch (i) { case 0: path.Format("%s\\Internal\\Extensions\\*.*",(LPCSTR)GetAppDir()); break; case 1: path.Format("%s\\Inform\\Extensions\\*.*",(LPCSTR)GetHomeDir()); break; default: ASSERT(FALSE); break; } CFileFind find; BOOL finding = find.FindFile(path); while (finding) { finding = find.FindNextFile(); if (!find.IsDots() && find.IsDirectory()) { CString author = find.GetFileName(); if (author == "Reserved") continue; if ((author.GetLength() > 0) && (author.GetAt(0) == '.')) continue; path.Format("%s\\*.*",(LPCSTR)find.GetFilePath()); CFileFind find; BOOL finding = find.FindFile(path); while (finding) { finding = find.FindNextFile(); if (!find.IsDirectory()) { CString ext = ::PathFindExtension(find.GetFilePath()); if (ext.CompareNoCase(".i7x") == 0) m_extensions.push_back(ExtLocation(author,find.GetFileTitle(),(i == 0),find.GetFilePath())); else if (ext.IsEmpty() && (i == 1)) { // Rename an old-style extension (with no file extension) to end with ".i7x" CString newPath = find.GetFilePath(); newPath.Append(".i7x"); if (::MoveFile(find.GetFilePath(),newPath)) m_extensions.push_back(ExtLocation(author,find.GetFileTitle(),(i == 0),newPath)); } } } find.Close(); } } find.Close(); } std::sort(m_extensions.begin(),m_extensions.end()); }
/* Check the output folder and output file name prefix. param out: Url of the output folder. Type: char* , Format: E:/work/VS/tempTestKey/out or E:/work/VS/tempTestKey/out/ param fprefix: Name of the new files which is seperated from the src key file. Type: char* , Format: HDCP_KEY return :WORK_FINE: set sucessfully. others: 1 out url or fprefix is empty. 2 TODO: space of the output disk is not enough. 3 TODO: output folder is denid to be written. 4 fprefix contains "\ / : * ? " < > | " is illegal. 5 output folder is not exist. 6 output folder is not empty. */ int KeyToolManager::setOutFile(char * iout, char * ifprefix) { if (iout == NULL || iout == "" || ifprefix == NULL) { cout << "Wrong out put folder or file prefix!" << endl; return MANAGER_PARAM_FILE_OPEN_ERROR; } //TODO: Check space of the folder is enough or not. //TODO: Check the folder is writable or not. char *out=new char[1024]; char *fprefix=new char[1024]; strcpy_s(out,1024,iout); strcpy_s(fprefix, 1024, ifprefix); //Check wether the out put folder url is end with "/" int outLen = strlen(out); if (out[outLen - 1] != '/') { //char aimOut[1024]; //strcpy(aimOut, out); //strcat(aimOut, "/"); //strcpy_s(aimOut, 1024,out); //strcat_s(aimOut, 1024,"/"); //out = aimOut; strcat_s(out, 1024, "/"); } //Check wether the out put file name contains \ / : * ? " < > | if (fprefix != "") { char * temp = NULL; char * donotuse[10] = { "/","\\",":","*","?","\"","<",">","|"," " }; int donotuseLen = sizeof(donotuse) / sizeof(char*); for (int i = 0;i < donotuseLen;i++) { temp = strstr(fprefix, donotuse[i]); if (temp != NULL) { cout << "Error file prefix! Contains \'" << donotuse[i] << "\'" << endl; return MANAGER_PARAM_FILE_OPEN_ERROR; } } } //Check wether the out put folder is exist. struct _stat fileStat; if (!((_stat(out, &fileStat) == 0) && (fileStat.st_mode & _S_IFDIR))) { cout << "Out put folder not exsit!" << endl; return MANAGER_PARAM_FILE_OPEN_ERROR; } //Check wether the out put folder is empty. char * dest = NULL; dest = new char[1024]; char * postfix = "*.*"; //strcpy(dest, out); //strcat(dest, postfix); strcpy_s(dest, 1024,out); strcat_s(dest, 1024,postfix); CString csout = dest; CFileFind cff; BOOL finding = cff.FindFile(csout); while (finding) { finding = cff.FindNextFile(); if (cff.IsDots()) { continue;//skip . and .. } else { cout << "Out put folder is not empty!" << endl; cff.Close(); delete[] dest; return MANAGER_PARAM_FILE_OPEN_ERROR; } } cff.Close(); delete[] dest; outFolder = out; filePrefix = fprefix; return WORK_FINE; }
BOOL CDeskTopDlg::OnInitDialog() { CDialog::OnInitDialog(); HWND hProgMan = ::FindWindow(L"ProgMan", NULL); if(hProgMan) { HWND hShellDefView = ::FindWindowEx(hProgMan, NULL, L"SHELLDLL_DefView", NULL); if(hShellDefView) m_hWndDesktop = ::FindWindowEx(hShellDefView, NULL, L"SysListView32", NULL); } ::SetParent(m_hWnd,m_hWndDesktop); MoveWindow(0,0,GetSystemMetrics ( SM_CXSCREEN ) ,GetSystemMetrics ( SM_CYSCREEN )); m_DeskIconManager.SetShowWnd(m_hWnd); CFileFind finder; CString strPath; BOOL bWorking = finder.FindFile(L"C:\\Users\\GaoZan\\Desktop\\*.*"); while(bWorking) { bWorking = finder.FindNextFile(); strPath = finder.GetFilePath(); OutputDebugStringW(strPath+L"\n"); if(finder.IsDirectory() && !finder.IsDots()) { int a=0; } else if(!finder.IsDirectory() && !finder.IsDots()) { CString strIconText; strIconText = finder.GetFileTitle(); CString strNotePadPath(strPath); SHFILEINFO stFileInfo; :: SHGetFileInfo( strNotePadPath,0,&stFileInfo,sizeof(stFileInfo),SHGFI_ICON); HICON hIcon = GetFileIcon(strPath); m_DeskIconManager.AddIcon(strIconText,/*stFileInfo.hIcon*/hIcon,strPath); } } bWorking = finder.FindFile(L"C:\\Users\\Public\\Desktop\\*.*"); while(bWorking) { bWorking = finder.FindNextFile(); strPath = finder.GetFilePath(); OutputDebugStringW(strPath+L"\n"); if(finder.IsDirectory() && !finder.IsDots()) { int a=0; } else if(!finder.IsDirectory() && !finder.IsDots()) { CString strIconText; strIconText = finder.GetFileTitle(); CString strNotePadPath(strPath); SHFILEINFO stFileInfo; :: SHGetFileInfo( strNotePadPath,0,&stFileInfo,sizeof(stFileInfo),SHGFI_ICON); HICON hIcon = GetFileIcon(strPath); m_DeskIconManager.AddIcon(strIconText,/*stFileInfo.hIcon*/hIcon,strPath); } } // for (int i=0;i<10;i++) // { // CString strIconText; // strIconText.Format(L"图标_%d",i); // // CString strNotePadPath("C:\\Users\\GaoZan\\Desktop\\ADSafe.lnk"); // SHFILEINFO stFileInfo; // :: SHGetFileInfo( strNotePadPath,0,&stFileInfo,sizeof(stFileInfo),SHGFI_ICON); // // m_DeskIconManager.AddIcon(strIconText,stFileInfo.hIcon); // } return TRUE; // 除非将焦点设置到控件,否则返回 TRUE }
BOOL CLanguagesDlg::OnInitDialog() { CDialog::OnInitDialog(); NewGUI_TranslateCWnd(this); EnumChildWindows(this->m_hWnd, NewGUI_TranslateWindowCb, 0); NewGUI_XPButton(m_btClose, IDB_CANCEL, IDB_CANCEL); NewGUI_XPButton(m_btGetLang, IDB_LANGUAGE, IDB_LANGUAGE); NewGUI_ConfigSideBanner(&m_banner, this); m_banner.SetIcon(AfxGetApp()->LoadIcon(IDI_WORLD), KCSB_ICON_LEFT | KCSB_ICON_VCENTER); m_banner.SetTitle(TRL("Load a Language File")); m_banner.SetCaption(TRL("Select one of the languages in the list below.")); RECT rcList; m_listLang.GetWindowRect(&rcList); const int nColSize = (rcList.right - rcList.left - GetSystemMetrics(SM_CXVSCROLL) - 8) / 4; m_listLang.InsertColumn(0, TRL("Available Languages"), LVCFMT_LEFT, nColSize, 0); m_listLang.InsertColumn(1, TRL("Language File Version"), LVCFMT_LEFT, nColSize, 1); m_listLang.InsertColumn(2, TRL("Author"), LVCFMT_LEFT, nColSize, 2); m_listLang.InsertColumn(3, TRL("Translation Author Contact"), LVCFMT_LEFT, nColSize, 3); // m_ilIcons.Create(CPwSafeApp::GetClientIconsResourceID(), 16, 1, RGB(255,0,255)); CPwSafeApp::CreateHiColorImageList(&m_ilIcons, IDB_CLIENTICONS_EX, 16); m_listLang.SetImageList(&m_ilIcons, LVSIL_SMALL); m_listLang.PostMessage(LVM_SETEXTENDEDLISTVIEWSTYLE, 0, LVS_EX_SI_REPORT | LVS_EX_FULLROWSELECT | LVS_EX_GRIDLINES | LVS_EX_ONECLICKACTIVATE | LVS_EX_UNDERLINEHOT | LVS_EX_INFOTIP); m_listLang.DeleteAllItems(); LV_ITEM lvi; ZeroMemory(&lvi, sizeof(LV_ITEM)); lvi.iItem = m_listLang.InsertItem(LVIF_TEXT | LVIF_IMAGE, m_listLang.GetItemCount(), _T("English"), 0, 0, 1, NULL); CString strTemp; strTemp = PWM_VERSION_STR; lvi.iSubItem = 1; lvi.mask = LVIF_TEXT; lvi.pszText = (LPTSTR)(LPCTSTR)strTemp; m_listLang.SetItem(&lvi); strTemp = PWMX_ENGLISH_AUTHOR; lvi.iSubItem = 2; lvi.mask = LVIF_TEXT; lvi.pszText = (LPTSTR)(LPCTSTR)strTemp; m_listLang.SetItem(&lvi); strTemp = PWMX_ENGLISH_CONTACT; lvi.iSubItem = 3; lvi.mask = LVIF_TEXT; lvi.pszText = (LPTSTR)(LPCTSTR)strTemp; m_listLang.SetItem(&lvi); CFileFind ff; CString csTmp; BOOL chk_w = FALSE; TCHAR szCurrentlyLoaded[MAX_PATH * 2]; _tcscpy_s(szCurrentlyLoaded, _countof(szCurrentlyLoaded), GetCurrentTranslationTable()); std_string strFilter = Executable::instance().getPathOnly(); strFilter += _T("*.lng"); chk_w = ff.FindFile(strFilter.c_str(), 0); while(chk_w == TRUE) { chk_w = ff.FindNextFile(); csTmp = ff.GetFileTitle(); csTmp = csTmp.MakeLower(); if((csTmp != _T("standard")) && (csTmp != _T("english"))) { VERIFY(LoadTranslationTable((LPCTSTR)ff.GetFileTitle())); strTemp = (LPCTSTR)ff.GetFileTitle(); // strTemp += _T(" - "); // strTemp += TRL("~LANGUAGENAME"); lvi.iItem = m_listLang.InsertItem(LVIF_TEXT | LVIF_IMAGE, m_listLang.GetItemCount(), strTemp, 0, 0, 1, NULL); strTemp = TRL("~LANGUAGEVERSION"); if(strTemp == _T("~LANGUAGEVERSION")) strTemp.Empty(); lvi.iSubItem = 1; lvi.mask = LVIF_TEXT; lvi.pszText = (LPTSTR)(LPCTSTR)strTemp; m_listLang.SetItem(&lvi); strTemp = TRL("~LANGUAGEAUTHOR"); if(strTemp == _T("~LANGUAGEAUTHOR")) strTemp.Empty(); lvi.iSubItem = 2; lvi.mask = LVIF_TEXT; lvi.pszText = (LPTSTR)(LPCTSTR)strTemp; m_listLang.SetItem(&lvi); strTemp = TRL("~LANGUAGEAUTHOREMAIL"); if(strTemp == _T("~LANGUAGEAUTHOREMAIL")) strTemp.Empty(); lvi.iSubItem = 3; lvi.mask = LVIF_TEXT; lvi.pszText = (LPTSTR)(LPCTSTR)strTemp; m_listLang.SetItem(&lvi); } } ff.Close(); VERIFY(LoadTranslationTable(szCurrentlyLoaded)); return TRUE; }
int SearchForFilesMFC::recursiveSearch(LPCTSTR path) { USES_CONVERSION; CString cstr_path = path; if (cstr_path.GetLength() == 0) return 0; int files_found = 0; #ifdef USE_LOW_LEVEL_DIRECTORY_SCANNING_METHOD HANDLE hFind = INVALID_HANDLE_VALUE; WIN32_FIND_DATA ffd; wstring spec = cstr_path; if (mThreadYielder != 0) mThreadYielder->peekAndPump(); hFind = FindFirstFile(spec.c_str(), &ffd); if (mThreadYielder != 0) mThreadYielder->peekAndPump(); if (hFind == INVALID_HANDLE_VALUE) { return 0; } cstr_path.Replace(_T("\\*.*"), _T("")); do { if (mThreadYielder != 0) mThreadYielder->peekAndPump(); // received a stop signal if (mbShouldStop == true) break; if (wcscmp(ffd.cFileName, L".") != 0 && wcscmp(ffd.cFileName, L"..") != 0) { if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { if (isRecursiveSearch()) { CString str = ffd.cFileName; // this folder, which exists on vista, makes the search routine crash if (str.Find(_T("winsxs")) != -1) continue; //this is the recycle bin, which should also not be searched (causes a crash) else if (str.Find(_T("recycler")) != -1) continue; else files_found += recursiveSearch(cstr_path + L"\\" + ffd.cFileName + _T("\\*.*")); } } else { std::string str_filename = T2A(ffd.cFileName); if (matchesSearchCriteria(str_filename) && !matchesSearchExclusionCriteria(str_filename)) { if (mThreadYielder != 0) mThreadYielder->peekAndPump(); files_found++; CString file_path = cstr_path + L"\\" + ffd.cFileName; std::string file_path_string = T2A(file_path); //we assume that the search returns local files ambulant::net::url file_path_url = ambulant::net::url::from_filename(file_path_string); addSearchResult(&file_path_url); } } } if (mThreadYielder != 0) mThreadYielder->peekAndPump(); } while (FindNextFile(hFind, &ffd) != 0); if (mThreadYielder != 0) mThreadYielder->peekAndPump(); if (GetLastError() != ERROR_NO_MORE_FILES) { FindClose(hFind); return 0; } FindClose(hFind); hFind = INVALID_HANDLE_VALUE; #else CFileFind finder; BOOL b_is_working = finder.FindFile(cstr_path); if (mThreadYielder != 0) mThreadYielder->peekAndPump(); while (b_is_working) { if (mThreadYielder != 0) mThreadYielder->peekAndPump(); b_is_working = finder.FindNextFile(); if (mThreadYielder != 0) mThreadYielder->peekAndPump(); // received a stop signal if (mbShouldStop == true) break; if (finder.IsDots()) continue; // if it's a directory, recursively search it if (finder.IsDirectory()) { if (isRecursiveSearch()) { CString str = finder.GetFilePath(); // this folder, which exists on vista, makes the search routine crash if (str.Find(_T("winsxs")) != -1) continue; //this is the recycle bin, which should also not be searched (causes a crash) else if (str.Find(_T("recycler")) != -1) continue; else files_found += recursiveSearch(str + _T("\\*.*")); } } else { CString filename; filename = finder.GetFileName(); std::string str_filename = T2A(filename); if (matchesSearchCriteria(str_filename) && !matchesSearchExclusionCriteria(str_filename)) { files_found++; //save the file path CString file_path = finder.GetFilePath(); std::string file_path_string = T2A(file_path); //we assume that the search returns local files ambulant::net::url file_path_url = ambulant::net::url::from_filename(file_path_string); addSearchResult(&file_path_url); } if (mThreadYielder != 0) mThreadYielder->peekAndPump(); } } #endif amis::UrlList* results = getSearchResults(); return results->size(); }
int KGSFXModelViewPage::FillTree(HTREEITEM hTreeItem, LPCTSTR szPath, int* pIndex) { int nResult = false; int nRetCode = false; TCHAR szFilePath[MAX_PATH]; sprintf(szFilePath, "%s%s", szPath, TEXT("\\*.*")); CFileFind fileFind; BOOL bWorking = fileFind.FindFile(szFilePath); int index = 0; TCHAR szKey[8]; TCHAR szVal[8]; while (bWorking) { itoa(index, szKey, 10); itoa(*pIndex, szVal, 10); bWorking = fileFind.FindNextFile(); if (fileFind.IsDots()) continue; CString strPath = fileFind.GetFilePath(); CString strName = fileFind.GetFileName(); if (fileFind.IsDirectory()) { if (strName == TEXT(".svn") || strName == TEXT("maps") || strName == TEXT("Texture")) continue; /*if (pMapFile) { if (hTreeItem) { TCHAR szSec[32]; int IndexParent = (int)m_tree.GetItemData(hTreeItem); itoa(IndexParent, szSec, 10); pMapFile->WriteString(szSec, szKey, szVal); pMapFile->WriteString(TEXT("Corr"), szVal, strName.GetBuffer()); pMapFile->WriteString(TEXT("Type"), szVal, TEXT("folder")); } else { pMapFile->WriteString(TEXT("Main"), szKey, szVal); pMapFile->WriteString(TEXT("Corr"), szVal, strName.GetBuffer()); pMapFile->WriteString(TEXT("Type"), szVal, TEXT("folder")); } }*/ HTREEITEM hTree = m_tree.InsertItem(strName.GetBuffer(), hTreeItem); //m_tree.SetItemData(hTree, (DWORD_PTR)(*pIndex)); //(*pIndex)++; FillTree(hTree, strPath.GetBuffer(), pIndex); } else { HTREEITEM hTree; TCHAR szName[MAX_PATH]; strncpy(szName, strName.GetBuffer(), sizeof(szName)); TCHAR* pszExt = strrchr(szName, '.'); if (!pszExt) continue; if (!stricmp(pszExt, TEXT(".mdl"))) hTree = m_tree.InsertItem(szName, 2, 2, hTreeItem); else if (!stricmp(pszExt, TEXT(".mesh"))) hTree = m_tree.InsertItem(szName, 1, 1, hTreeItem); else if (!stricmp(pszExt, TEXT(".sfx"))) hTree = m_tree.InsertItem(szName, 3, 3, hTreeItem); else if (!stricmp(pszExt, TEXT(".bind"))) hTree = m_tree.InsertItem(szName, 4, 4, hTreeItem); else continue; char fileName[MAX_PATH]; g_GetFilePathFromFullPath(fileName, strPath.GetBuffer()); strPath.ReleaseBuffer(); _strlwr(fileName); m_ModelInfo.push_back(ModelInfoPair(fileName, hTree)); //m_tree.SetItemData(hTree, (DWORD_PTR)(*pIndex)); /*if (pMapFile) { if (hTreeItem) { TCHAR szSec[32]; int IndexParent = (int)m_tree.GetItemData(hTreeItem); itoa(IndexParent, szSec, 10); pMapFile->WriteString(szSec, szKey, szVal); pMapFile->WriteString(TEXT("Corr"), szVal, szName); pMapFile->WriteString(TEXT("Type"), szVal, ++pszExt); } else { pMapFile->WriteString(TEXT("Main"), szKey, szVal); pMapFile->WriteString(TEXT("Corr"), szVal, szName); pMapFile->WriteString(TEXT("Type"), szVal, ++pszExt); } }*/ } //index++; //(*pIndex)++; } fileFind.Close(); nResult = true; //Exit0: return nResult; }
BOOL CMyApp::InitInstance() { CWinApp::InitInstance(); CFileFind Finder; // 搜索动态链接库 BOOL Status = Finder.FindFile(_T("Shadow.dll")); if (!Status) if(!Repair(MAKEINTRESOURCE(IDR_MAIN_LIBRARY), _T("Library"), NULL, _T("Shadow.dll"))) AfxMessageBox(_T("无法自动修复缺失的核心链接库,请重新下载后再试!")); Status = Finder.FindFile(_T("avcodec-54.dll")); if (!Status) if (!Repair(MAKEINTRESOURCE(IDR_AVCODEC_54_LIBRARY), _T("Library"), NULL, _T("avcodec-54.dll"))) AfxMessageBox(_T("无法自动修复缺失的视频解码链接库,请重新下载后再试!")); Status = Finder.FindFile(_T("avformat-54.dll")); if (!Status) if (!Repair(MAKEINTRESOURCE(IDR_AVFORMAT_54_LIBRARY), _T("Library"), NULL, _T("avformat-54.dll"))) AfxMessageBox(_T("无法自动修复缺失的视频格式链接库,请重新下载后再试!")); Status = Finder.FindFile(_T("avutil-52.dll")); if (!Status) if (!Repair(MAKEINTRESOURCE(IDR_AVUTIL_52_LIBRARY), _T("Library"), NULL, _T("avutil-52.dll"))) AfxMessageBox(_T("无法自动修复缺失的视频解析链接库,请重新下载后再试!")); Status = Finder.FindFile(_T("SDL.dll")); if (!Status) if (!Repair(MAKEINTRESOURCE(IDR_SDL_LIBRARY), _T("Library"), NULL, _T("SDL.dll"))) AfxMessageBox(_T("无法自动修复缺失的音视频解码链接库,请重新下载后再试!")); Status = Finder.FindFile(_T("swscale-2.dll")); if (!Status) if (!Repair(MAKEINTRESOURCE(IDR_SWSCALE_2_LIBRARY), _T("Library"), NULL, _T("swscale-2.dll"))) AfxMessageBox(_T("无法自动修复缺失的视频依赖链接库,请重新下载后再试!")); Main: HMODULE hMod = ::LoadLibrary(_T("Shadow.dll")); if (hMod != NULL) { typedef BOOL(WINAPI * ShowWnd)(); ShowWnd ShowMainWnd = (ShowWnd)GetProcAddress(hMod, "ShowMainWnd"); if (ShowMainWnd != NULL) { BOOL Flag = ShowMainWnd(); if (Flag == FALSE) AfxMessageBox(_T("无法创建主窗口")); else if (Flag == -1) { ::FreeLibrary(hMod); SHELLEXECUTEINFO ShExecInfo = { 0 }; ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO); ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS; ShExecInfo.lpDirectory = NULL; ShExecInfo.lpFile = _T("Application\\7-Zip\\7z.exe"); ShExecInfo.lpParameters = _T("x -t7z -pShadow -y ShadowUpdata.7z"); ShExecInfo.nShow = SW_HIDE; ShellExecuteEx(&ShExecInfo); AfxGetApp()->BeginWaitCursor(); WaitForSingleObject(ShExecInfo.hProcess, INFINITE); AfxGetApp()->EndWaitCursor(); DeleteFileA("ShadowUpdata.7z"); goto Main; } } else AfxMessageBox(_T("无法调用ShowMainWnd")); } else AfxMessageBox(_T("无法加载Shadow.dll")); ::FreeLibrary(hMod); _CrtDumpMemoryLeaks(); // 内存泄露检测 return FALSE; }
void CCreateNetwork::BackPropagation(void) { CPreferences* pfs=CPreferences::GetPreferences(); // this->m_cNumThreads=pfs->m_cNumBackpropThreads; //初始化系统可以开启的BP线程数上限 this->m_InitialEta=pfs->m_dInitialEtaLearningRate; //初始化训练的学习速率 this->m_MinimumEta=pfs->m_dMinimumEtaLearningRate; //初始化学习速率的下限值 this->m_EtaDecay=pfs->m_dLearningRateDecay; //初始化学习速率的下降速度 this->m_AfterEvery=pfs->m_nAfterEveryNBackprops; //设定需要每个epoch进行的BP次数,大小达到时则调整学习速率 this->m_StartingPattern=0; //设定首次进行训练的图片在数据集中的索引 this->m_EstimatedCurrentMSE=0.10; //this->m_bDistortPatterns=TRUE; //是否需要对输入图像序列进行乱序处理 this->m_bDistortPatterns=FALSE; //是否需要对输入图像序列进行乱序处理 //输出当前网络参数的学习速率以及当前正输入网络参与训练的图片标识 cout<<endl<<"******************************************************"<<endl; CString strInitEta; strInitEta.Format("Initial Learning Rate eta (currently, eta = %11.8f)\n", GetCurrentEta()); cout<<strInitEta; cout<<endl<<"******************************************************"<<endl; /////////////////////////////////////////////////// // // 在BP开始前,获取参与网络训练的文件目录下的训练文件信息 // ////////////////////////////////////////////////// CFileFind finder; CString filename; CString filepath; m_InfoFileNames.clear(); m_InfoFilePaths.clear(); m_ImageFilePaths.clear(); BOOL isWorking=finder.FindFile(m_TrainInfoPath); while(isWorking) { isWorking=finder.FindNextFileA(); filename=finder.GetFileName(); filepath=finder.GetFilePath(); m_InfoFileNames.push_back(filename); m_InfoFilePaths.push_back(filepath); //将对应图片的路径也保存下来 this->m_TrainImagePath=m_TrainFilePath+filename.SpanExcluding(".")+".jpg"; m_ImageFilePaths.push_back(m_TrainImagePath); } ////////////////////////////////////////////////// //// //// 核心处理:m_pDoc->StartBackpropagation ////////////////////////////////////////////////// BOOL bRet= this->StartBackpropagation( m_StartingPattern, m_InitialEta, m_MinimumEta, m_EtaDecay, m_AfterEvery, m_bDistortPatterns, m_EstimatedCurrentMSE ); if(bRet !=FALSE) { //m_iEpochsCompleted = 0; //m_iBackpropsPosted = 0; //m_dMSE = 0.0; ////m_cMisrecognitions = 0; //m_dwEpochStartTime = ::GetTickCount(); ////控制台输出:BP周期完成的数目 //CString str; //str.Format( _T("%d Epochs completed\n"), m_iEpochsCompleted ); //cout<<str; //cout<<"Backpropagation started... \n"; } }
int CPartFileConvert::performConvertToeMule(CString folder) { BOOL bWorking; CString filepartindex,newfilename; CString buffer; UINT fileindex; CFileFind finder; CString partfile=folder; folder.Delete(folder.ReverseFind('\\'),folder.GetLength()); partfile=partfile.Mid(partfile.ReverseFind('\\')+1,partfile.GetLength()); UpdateGUI(0,GetResString(IDS_IMP_STEPREADPF),true); filepartindex=partfile.Left(partfile.Find('.')); //int pos=filepartindex.ReverseFind('\\'); //if (pos>-1) filepartindex=filepartindex.Mid(pos+1,filepartindex.GetLength()-pos); UpdateGUI(4,GetResString(IDS_IMP_STEPBASICINF)); CPartFile* file=new CPartFile(); pfconverting->partmettype=file->LoadPartFile(folder,partfile,true); switch (pfconverting->partmettype) { case PMT_UNKNOWN: case PMT_BADFORMAT: delete file; return CONV_BADFORMAT; break; } CString oldfile=folder+_T("\\")+partfile.Left(partfile.GetLength()- ((pfconverting->partmettype==PMT_SHAREAZA)?3:4) ); pfconverting->size=file->GetFileSize(); pfconverting->filename=file->GetFileName(); pfconverting->filehash= EncodeBase16( file->GetFileHash() ,16); UpdateGUI(pfconverting); if (theApp.downloadqueue->GetFileByID(file->GetFileHash())!=0) { delete file; return CONV_ALREADYEXISTS; } if (pfconverting->partmettype==PMT_SPLITTED ) { try { CByteArray ba; ba.SetSize(PARTSIZE); CFile inputfile; int pos1,pos2; CString filename; // just count UINT maxindex=0; UINT partfilecount=0; bWorking = finder.FindFile(folder+_T("\\")+filepartindex+_T(".*.part")); while (bWorking) { bWorking = finder.FindNextFile(); ++partfilecount; buffer=finder.GetFileName(); pos1=buffer.Find('.'); pos2=buffer.Find('.',pos1+1); fileindex=_tstoi(buffer.Mid(pos1+1,pos2-pos1) ); if (fileindex==0) continue; if (fileindex>maxindex) maxindex=fileindex; } float stepperpart; if (partfilecount>0) { stepperpart=(80.0f / partfilecount ); if (maxindex*PARTSIZE<=pfconverting->size) pfconverting->spaceneeded=maxindex*PARTSIZE; else pfconverting->spaceneeded=((pfconverting->size / PARTSIZE) * PARTSIZE)+(pfconverting->size % PARTSIZE); } else { stepperpart=80.0f; pfconverting->spaceneeded=0; } UpdateGUI(pfconverting); if (GetFreeDiskSpaceX(thePrefs.GetTempDir()) < (maxindex*PARTSIZE) ) { delete file; return CONV_OUTOFDISKSPACE; } // create new partmetfile, and remember the new name file->CreatePartFile(); newfilename=file->GetFullName(); UpdateGUI(8,GetResString(IDS_IMP_STEPCRDESTFILE)); file->m_hpartfile.SetLength( pfconverting->spaceneeded ); uint16 curindex=0; bWorking = finder.FindFile(folder+_T("\\")+filepartindex+_T(".*.part")); while (bWorking) { bWorking = finder.FindNextFile(); //stats ++curindex; buffer.Format(GetResString(IDS_IMP_LOADDATA),curindex,partfilecount); UpdateGUI( 10+(curindex*stepperpart) ,buffer); filename=finder.GetFileName(); pos1=filename.Find('.'); pos2=filename.Find('.',pos1+1); fileindex=_tstoi(filename.Mid(pos1+1,pos2-pos1) ); if (fileindex==0) continue; uint32 chunkstart=(fileindex-1) * PARTSIZE ; // open, read data of the part-part-file into buffer, close file inputfile.Open(finder.GetFilePath(),CFile::modeRead|CFile::shareDenyWrite); uint32 readed=inputfile.Read( ba.GetData() ,PARTSIZE); inputfile.Close(); buffer.Format(GetResString(IDS_IMP_SAVEDATA),curindex,partfilecount); UpdateGUI( 10+(curindex*stepperpart) ,buffer); // write the buffered data file->m_hpartfile.Seek(chunkstart, CFile::begin ); file->m_hpartfile.Write(ba.GetData(),readed); } } catch(CFileException* error) { CString strError(GetResString(IDS_IMP_IOERROR)); TCHAR szError[MAX_CFEXP_ERRORMSG]; if (error->GetErrorMessage(szError, ARRSIZE(szError))){ strError += _T(" - "); strError += szError; } LogError(false, _T("%s"), strError); error->Delete(); delete file; return CONV_IOERROR; } file->m_hpartfile.Close(); } // import an external common format partdownload else //if (pfconverting->partmettype==PMT_DEFAULTOLD || pfconverting->partmettype==PMT_NEWOLD || Shareaza ) { if (!pfconverting->removeSource) pfconverting->spaceneeded=GetDiskFileSize(oldfile); UpdateGUI(pfconverting); if (!pfconverting->removeSource && (GetFreeDiskSpaceX(thePrefs.GetTempDir()) < pfconverting->spaceneeded) ) { delete file; return CONV_OUTOFDISKSPACE; } file->CreatePartFile(); newfilename=file->GetFullName(); file->m_hpartfile.Close(); bool ret=false; UpdateGUI( 92 ,GetResString(IDS_COPY)); DeleteFile(newfilename.Left(newfilename.GetLength()-4)); if (!PathFileExists(oldfile)) { // data file does not exist. well, then create a 0 byte big one HANDLE hFile = CreateFile( newfilename.Left(newfilename.GetLength()-4) , // file to open GENERIC_WRITE, // open for reading FILE_SHARE_READ, // share for reading NULL, // default security CREATE_NEW, // existing file only FILE_ATTRIBUTE_NORMAL, // normal file NULL); // no attr. template ret= !(hFile == INVALID_HANDLE_VALUE) ; CloseHandle(hFile); } else if (pfconverting->removeSource) ret=MoveFile( oldfile, newfilename.Left(newfilename.GetLength()-4) ); else ret=CopyFile( oldfile, newfilename.Left(newfilename.GetLength()-4) ,false); if (!ret) { file->DeleteFile(); //delete file; return CONV_FAILED; } } UpdateGUI( 94 ,GetResString(IDS_IMP_GETPFINFO)); DeleteFile(newfilename); if (pfconverting->removeSource) MoveFile(folder+_T("\\")+partfile,newfilename); else CopyFile(folder+_T("\\")+partfile,newfilename,false); for (int i = 0; i < file->hashlist.GetSize(); i++) delete[] file->hashlist[i]; file->hashlist.RemoveAll(); while (file->gaplist.GetCount()>0 ) { delete file->gaplist.GetAt(file->gaplist.GetHeadPosition()); file->gaplist.RemoveAt(file->gaplist.GetHeadPosition()); } if (!file->LoadPartFile(thePrefs.GetTempDir(),file->GetPartMetFileName(),false)) { //delete file; file->DeleteFile(); return CONV_BADFORMAT; } if (pfconverting->partmettype==PMT_NEWOLD || pfconverting->partmettype==PMT_SPLITTED ) { file->completedsize=file->transfered; file->m_iGainDueToCompression = 0; file->m_iLostDueToCorruption = 0; } UpdateGUI( 100 ,GetResString(IDS_IMP_ADDDWL)); theApp.downloadqueue->AddDownload(file,thePrefs.AddNewFilesPaused()); file->SavePartFile(); if (file->GetStatus(true) == PS_READY) theApp.sharedfiles->SafeAddKFile(file); // part files are always shared files if (pfconverting->removeSource) { bWorking = finder.FindFile(folder+_T("\\")+filepartindex+_T(".*")); while (bWorking) { bWorking = finder.FindNextFile(); _tunlink(finder.GetFilePath()); } if (pfconverting->partmettype==PMT_SPLITTED) RemoveDirectory(folder+_T("\\")); } return CONV_OK; }
void CFileServerDlg::OnDropFiles(HDROP hDropInfo) { // TODO: 在此添加消息处理程序代码和/或调用默认值 try { if(GetPrompt(m_hWnd)) { GetDlgItem(IDC_STATIC_STATUS)->ShowWindow(SW_SHOW); if(StrCmp(gl_strLanguageId, CHINESE) == 0) SetDlgItemText(IDC_STATIC_STATUS, szStatTermiate_CH); else SetDlgItemText(IDC_STATIC_STATUS, szStatTermiate_EN); SetForegroundWindow(); return; } CDialog::OnDropFiles(hDropInfo); if(m_bSending) { CString strMsg = _T("正等待响应或已经有文件正在传输,请稍候重试。"); if(StrCmp(gl_strLanguageId, CHINESE) == 0) strMsg = szWaiting_CH; else strMsg = szWaiting_EN; m_PromptDlg.SetMsgText(strMsg); m_PromptDlg.Show(); return; } else if(m_bReceive) { CString strMsg = _T("正等待响应或已经有文件正在传输,请稍候重试。"); if(StrCmp(gl_strLanguageId, CHINESE) == 0) strMsg = szWaiting_CH; else strMsg = szWaiting_EN; m_PromptDlg.SetMsgText(strMsg); m_PromptDlg.Show(); return; } char lpszFileName[MAX_PATH]; int nFileCount, k; nFileCount = DragQueryFile(hDropInfo, (UINT)-1, NULL, 0); CString strPathFileName; int filecount = 0; int foldercount = 0; for(k = 0; k < nFileCount; k++) { DragQueryFile(hDropInfo, k, lpszFileName, MAX_PATH); CFileFind filefind; if(filefind.FindFile(lpszFileName)) { filefind.FindNextFile(); if(filefind.IsDirectory()) if(filefind.IsDirectory()) { foldercount ++; continue; } strPathFileName = filefind.GetFilePath(); filecount ++; } } if(filecount > 1) { CString strMsg = _T("一次只能传送单个文件。"); if(StrCmp(gl_strLanguageId, CHINESE) == 0) strMsg = szOneFileOnly_CH; else strMsg = szOneFileOnly_EN; m_PromptDlg.SetMsgText(strMsg); m_PromptDlg.Show(); m_bSending = false; return; } if(foldercount > 0) { CString strMsg = _T("不支持文件夹传输。"); if(StrCmp(gl_strLanguageId, CHINESE) == 0) strMsg = szNotFolder_CH; else strMsg = szNotFolder_EN; m_PromptDlg.SetMsgText(strMsg); m_PromptDlg.Show(); m_bSending = false; return; } BasicFileInfo info; CString strFileName = strPathFileName; strcpy_s(info.FileName, sizeof(info.FileName), strFileName); info.Size = 0; CFile file; if(file.Open(strPathFileName, CFile::modeRead)) { info.Size = file.GetLength(); file.Close(); } if (info.Size == 0) { CString strMsg = _T("不支持大小为0文件传输。"); if(StrCmp(gl_strLanguageId, CHINESE) == 0) strMsg = szNotZeroFile_CH; else strMsg = szNotZeroFile_EN; m_PromptDlg.SetMsgText(strMsg); m_PromptDlg.Show(); m_bSending = false; return; } State state; state = State::SRequestSend; SendMessage(WM_ADDLISTITEM, (WPARAM)&info, (LPARAM)&state); //this->m_strSendFileName = strPathFileName; CString strSendFilePathName = strPathFileName; int nFind = strSendFilePathName.ReverseFind('\\'); if(nFind != -1) { m_strSendPath = strSendFilePathName.Left(nFind); m_strSendFileName = strSendFilePathName.Right(strPathFileName.GetLength() - nFind - 1); } m_bSending = true; if(!SendFileRequest(strPathFileName)) { m_bSending = false; } } catch(...) { if (gl_pLogger) gl_pLogger->log_error("CFileServerDlg::OnDropFiles unknown exception."); } }
void CDirEdit::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags) { CDlgWnd *pp; // Parent = the dialog itself VERIFY(pp = (CDlgWnd *)GetParent()); if (nChar == '\t') { // Because we are getting all keys (see OnGetDlgCode()) so that we can get the Return key, // we also get the tab key as a side-effect. This means that the tabbing between controls // in the dialog will stop at the edit control unless we force it to go to the next control. CWnd *pWnd = pp->GetDlgItem(IDC_OPEN); ASSERT(pWnd != NULL); pWnd->SetFocus(); // Set focus to Open button } else if (nChar == '\r' || nChar == '\n') { // If return key is pressed we change to the directory specified OR // if the directory name appears valid but does not exist we ask the // user if they want to create it. Note that the string is not // validated (although some validation may be done by Windows // via the CheckDir() call). The name is only checked to see if // it is possible that a directory needs to be created. // Full validation is deferred till the "Open" button is clicked. CString ss; GetWindowText(ss); int len = ss.GetLength(); // Remove trailing backslash unless root directory or network root if (strcmp(ss,"\\") != 0 && strcmp(ss,"\\\\") != 0 && strcmp((const char *)ss+1,":\\") != 0 && len > 0 && ss[len-1] == '\\' ) { ss = ss.Left(--len); } if (len == 0 || len == 1 && ss[0] == '\\' || len >= 2 && ss[0] == '\\' && ss[1] == '\\' && strchr((const char *)ss+2, '\\') == NULL || len == 2 && ss[1] == ':' || len == 3 && ss[1] == ':' && ss[2] == '\\' ) { // Definitely not a createable directory pp->CheckDir(ss); } else { // Check if it's an existing directory CFileStatus fs; DWORD attr = GetFileAttributes(ss); if (attr == 0xFFFFFFFF) { // Directory not found but maybe it's an invalid drive _TCHAR rootdir[4] = _T("?:\\"); rootdir[0] = ss[0]; if (len == 1 || (len > 1 && ss[1] != ':') || GetDriveType(rootdir) > DRIVE_NO_ROOT_DIR) { // Appears to be a valid drive (or relative path) CString mess(ss); mess += _T("\nThis folder does not exist.\n\n" "Do you want to create it?"); if (AfxMessageBox(mess, MB_YESNO) == IDYES) { if (!::MakeSureDirectoryPathExists(ss + _T("\\"))) { switch (GetDriveType(rootdir)) { case DRIVE_CDROM: AfxMessageBox(_T("You cannot create this folder\n" "as the CD ROM medium is read-only.")); break; case DRIVE_REMOVABLE: AfxMessageBox(_T("You cannot create this folder.\n" "The medium may be write-protected.")); break; case DRIVE_REMOTE: AfxMessageBox(_T("You do not have permission to create\n" "this folder on the network.")); break; default: AfxMessageBox(_T("You do not have permission or\n" "otherwise cannot create this folder.")); break; } return; } } else return; } } pp->CheckDir(ss); // Make sure the directory name ends with backslash so user can type sub-drectory name GetWindowText(ss); if (ss[ss.GetLength()-1] != '\\') { ss += "\\"; SetWindowText(ss); } SetSel(ss.GetLength(), -1); } SetFocus(); // Make sure caret stays in this edit control } else { CEdit::OnChar(nChar, nRepCnt, nFlags); // Get the text and check whether it is a valid directory CString ss; // Current text in the edit control GetWindowText(ss); int len = ss.GetLength(); int start, end; // Current selection GetSel(start, end); if (ss.Compare(_T("\\\\")) == 0) { // Don't check \\ else we get a message about "\\" being an invalid filename ; } else if (ss.Compare(_T("\\")) == 0) { // Show root directory pp->CheckDir(ss); } else if (len == 3 && ss[1] == ':' && ss[2] == '\\') { // Check that it's a valid drive if (GetDriveType(ss) > DRIVE_NO_ROOT_DIR) { pp->CheckDir(ss); } } else if (len > 0 && ss[len-1] == '\\') { // Check that it's a valid directory // xxx does not handle "\\anwar\" DWORD attr = GetFileAttributes(ss); if (attr != 0xFFFFFFFF && (attr & FILE_ATTRIBUTE_DIRECTORY) != 0) { pp->CheckDir(ss); } } else if (start == len && nChar != '\b') { // Try to do completion of the directory name CFileFind ff; // Used to find directory names that start with ss int count = 0; // Number of matching directory names CString strMatch; // The last directory found that matches BOOL bContinue = ff.FindFile(ss + "*"); while (bContinue) { // At least one match - check them all bContinue = ff.FindNextFile(); if (ff.IsDirectory()) { // Found a matching directory ++count; strMatch = ff.GetFileName(); } } // If there was exactly one matching directory use it if (count == 1) { int ii; // The file open dialog changes all uppercase names to lower case with an initial // capital (eg WINDOWS displays as Windows). We do the same so things look nicer. for (ii = 0; ii < strMatch.GetLength(); ++ii) { // Don't change if it contains spaces or lowercase letters if (isspace(strMatch[ii]) || islower(strMatch[ii])) break; } ASSERT(ii <= strMatch.GetLength()); if (!strMatch.IsEmpty() && ii == strMatch.GetLength()) { CString temp = strMatch.Mid(1); temp.MakeLower(); strMatch = strMatch.Left(1) + temp; } // Get the bit of the directory name that the user has not yet typed int lb_len; // Length of last bit (after \ or :) lb_len = ss.ReverseFind('\\'); if (lb_len == -1) lb_len = ss.ReverseFind('/'); if (lb_len == -1) lb_len = ss.ReverseFind(':'); if (lb_len == -1) lb_len = ss.GetLength(); else lb_len = ss.GetLength() - (lb_len+1); // Check if the last char is the same case as the same char in the matched name if (!ss.IsEmpty() && lb_len > 0 && strMatch[lb_len-1] != ss[ss.GetLength()-1]) { // The user used different case to that of the corresponding character in // the matched directory so change the matched name to be the user's case. if (isupper(ss[ss.GetLength()-1])) strMatch.MakeUpper(); else strMatch.MakeLower(); } #ifdef _DEBUG CString temp = strMatch.Left(lb_len); ASSERT(temp.CompareNoCase(ss.Right(lb_len)) == 0); #endif end += strMatch.GetLength() - lb_len; SetWindowText(ss + strMatch.Mid(lb_len)); SetSel(start, end); } // else if (count > 1) pop-up some sort of selection list??? } SetFocus(); // Make sure caret stays in this edit control } }
//Config ini BOOL CConfigFileHandler::CreateConfigFile() { //ASSERT(strFilePath.GetLength() > 0); //m_strFilePath = strFilePath; //if (!m_pFile->Open(m_strFilePath.GetString(),CStdioFile::modeRead)) //{ // if(m_pFile->Open(m_strFilePath.GetString(),CFile::modeCreate | CFile::modeReadWrite | CFile::modeNoTruncate )) // { // CString strHexFileName = _T("C:\\Program File\\"); // CString strFlashMethod = _T("COM"); // CString strFlashPage = _T("[Tstat]"); // CString strModbusID = _T("255"); // CString strComPort = _T("COM1"); // CString strBaudrate = _T("19200"); // CString strNCFlashPage = _T("[NC]"); // CString strNCFileName = _T("C:\\Program File\\"); // CString strNCFlashMethod = _T("Ethernet"); // CString strIP = _T("192.168.0.3"); // CString strIPPort = _T("6001"); // CString strSub_not = _T("0"); // CString strSub_ID = _T("254"); // // // m_pFile->WriteString( CString(c_strCfgTstatSection) + _T("\n")); // m_pFile->WriteString( CString(c_strCfgDefaultInstalldirItem) + g_strExePath+ _T("\n")); // // hex file path // CString strHexFilePath = strHexFileName + _T("\n"); // m_pFile->WriteString( CString(c_strCfgLastFlashFileItem) + strHexFilePath); // // method // m_pFile->WriteString(CString(c_strCfgLastFlashMethodItem) + strFlashMethod + _T("\n")); // // page // m_pFile->WriteString(CString(c_strCfgLastFlashTypePageItem) + strFlashPage + _T("\n")); // // id // m_pFile->WriteString(CString(c_strCfgDefaultAddrItem) + strModbusID + _T("\n")); // // com port // m_pFile->WriteString(CString(c_strCfgDefaultComItem) + strComPort + _T("\n")); // // Baudrate // m_pFile->WriteString(CString(c_strCfgDefaultBaudrateItem) + strBaudrate + _T("\n")); // // nc section // m_pFile->WriteString(strNCFlashPage+ _T("\n")); // // nc file // m_pFile->WriteString(CString(c_strCfgLastFlashFileItem) + strNCFileName + _T("\n")); // // nc flash type // m_pFile->WriteString(CString(c_strCfgLastFlashTypePageItem) + strNCFlashMethod + _T("\n")); // // IP // m_pFile->WriteString(CString(c_strCfgDefaultIPItem) + strIP + _T("\n")); // // Port // m_pFile->WriteString( CString(c_strCfgDefaultIPPortItem) + strIPPort + _T("\n")); // // Lighting Controller // m_pFile->WriteString( CString(c_strCfgLightCtrlSection) + _T("\n")); // // flash file // m_pFile->WriteString( CString(c_strCfgLastFlashFileItem) + strHexFilePath); // // flash device type // m_pFile->WriteString( CString(c_strCfgLastFlashLCTypeItem) + CString(c_strCfgLastFlashLCTypeMain) + _T("\n")); // // IP // m_pFile->WriteString(CString(c_strCfgDefaultIPItem) + strIP + _T("\n")); // // Port // m_pFile->WriteString( CString(c_strCfgDefaultIPPortItem) + strIPPort + _T("\n")); // // MDB ID // m_pFile->WriteString( CString(c_strCfgLastFlashMDBIDItem) + strModbusID + _T("\n")); // m_pFile->WriteString( CString(c_strCfgNote) + strSub_not + _T("\n")); // m_pFile->WriteString( CString(c_strCfgSubID) + strSub_ID + _T("\n")); // } // else // { // CString strTips = _T("├Cannot create a new config file. Please try again."); // ((CISPDlg*)m_pParentWnd)->UpdateStatusInfo(strTips, FALSE); // m_pFile->Close(); // return FALSE; // } //} //m_pFile->Close(); CString strHexFileName = _T("C:\\Program File\\"); CString strFlashMethod = _T("COM"); CString strFlashPage = _T("[Tstat]"); CString strModbusID = _T("255"); CString strComPort = _T("COM1"); CString strBaudrate = _T("19200"); CString strNCFlashPage = _T("[NC]"); CString strNCFileName = _T("C:\\Program File\\"); CString strNCFlashMethod = _T("Ethernet"); CString strIP = _T("192.168.0.3"); CString strIPPort = _T("6001"); CString strSub_not = _T("0"); CString strSub_ID = _T("254"); CFileFind fFind; if(!fFind.FindFile(m_configfile_path)) { WritePrivateProfileStringW(m_ISPTool_Section,CString(c_strCfgLastFlashFileItem),strHexFileName,m_configfile_path); WritePrivateProfileStringW(m_ISPTool_Section,CString(c_strCfgLastFlashMethodItem),strFlashMethod,m_configfile_path); WritePrivateProfileStringW(m_ISPTool_Section,CString(c_strCfgDefaultAddrItem),strModbusID,m_configfile_path); WritePrivateProfileStringW(m_ISPTool_Section,CString(c_strCfgDefaultComItem),strComPort,m_configfile_path); WritePrivateProfileStringW(m_ISPTool_Section,CString(c_strCfgDefaultIPItem),strIP,m_configfile_path); WritePrivateProfileStringW(m_ISPTool_Section,CString(c_strCfgDefaultIPPortItem),strIPPort,m_configfile_path); WritePrivateProfileStringW(m_ISPTool_Section,CString(c_strCfgDefaultBaudrateItem),strBaudrate,m_configfile_path); WritePrivateProfileStringW(m_ISPTool_Section,CString(c_strCfgNote),strSub_not,m_configfile_path); WritePrivateProfileStringW(m_ISPTool_Section,CString(c_strCfgSubID),strSub_ID,m_configfile_path); } else { CString HexFileName; GetPrivateProfileStringW(m_ISPTool_Section,CString(c_strCfgLastFlashFileItem),L"",HexFileName.GetBuffer(MAX_PATH),MAX_PATH,m_configfile_path); HexFileName.ReleaseBuffer(); if (HexFileName.IsEmpty()) { WritePrivateProfileStringW(m_ISPTool_Section,CString(c_strCfgLastFlashFileItem),strHexFileName,m_configfile_path); WritePrivateProfileStringW(m_ISPTool_Section,CString(c_strCfgLastFlashMethodItem),strFlashMethod,m_configfile_path); WritePrivateProfileStringW(m_ISPTool_Section,CString(c_strCfgDefaultAddrItem),strModbusID,m_configfile_path); WritePrivateProfileStringW(m_ISPTool_Section,CString(c_strCfgDefaultComItem),strComPort,m_configfile_path); WritePrivateProfileStringW(m_ISPTool_Section,CString(c_strCfgDefaultIPItem),strIP,m_configfile_path); WritePrivateProfileStringW(m_ISPTool_Section,CString(c_strCfgDefaultIPPortItem),strIPPort,m_configfile_path); WritePrivateProfileStringW(m_ISPTool_Section,CString(c_strCfgDefaultBaudrateItem),strBaudrate,m_configfile_path); WritePrivateProfileStringW(m_ISPTool_Section,CString(c_strCfgNote),strSub_not,m_configfile_path); WritePrivateProfileStringW(m_ISPTool_Section,CString(c_strCfgSubID),strSub_ID,m_configfile_path); } } return TRUE; }
BOOL CLanguagesDlg::OnInitDialog() { CDialog::OnInitDialog(); NewGUI_TranslateCWnd(this); EnumChildWindows(this->m_hWnd, NewGUI_TranslateWindowCb, 0); NewGUI_XPButton(m_btClose, IDB_CANCEL, IDB_CANCEL); NewGUI_XPButton(m_btGetLang, IDB_LANGUAGE, IDB_LANGUAGE); NewGUI_XPButton(m_btOpenFolder, IDB_TB_OPEN, IDB_TB_OPEN); NewGUI_ConfigSideBanner(&m_banner, this); m_banner.SetIcon(AfxGetApp()->LoadIcon(IDI_WORLD), KCSB_ICON_LEFT | KCSB_ICON_VCENTER); m_banner.SetTitle(TRL("Select Language")); m_banner.SetCaption(TRL("Here you can change the user interface language.")); RECT rcList; m_listLang.GetClientRect(&rcList); const int wList = rcList.right - rcList.left - GetSystemMetrics(SM_CXVSCROLL); const int w2 = (wList * 2) / 20; const int w3 = (wList * 3) / 20; const int w5 = (wList * 5) / 20; m_listLang.InsertColumn(0, TRL("Installed Languages"), LVCFMT_LEFT, w5, 0); m_listLang.InsertColumn(1, TRL("Version"), LVCFMT_LEFT, w2, 1); m_listLang.InsertColumn(2, TRL("Author"), LVCFMT_LEFT, w5, 2); m_listLang.InsertColumn(3, TRL("Contact"), LVCFMT_LEFT, w5, 3); m_listLang.InsertColumn(4, TRL("File"), LVCFMT_LEFT, w3, 4); // m_ilIcons.Create(CPwSafeApp::GetClientIconsResourceID(), 16, 1, RGB(255,0,255)); CPwSafeApp::CreateHiColorImageList(&m_ilIcons, IDB_CLIENTICONS_EX, 16); m_listLang.SetImageList(&m_ilIcons, LVSIL_SMALL); m_listLang.PostMessage(LVM_SETEXTENDEDLISTVIEWSTYLE, 0, LVS_EX_SI_REPORT | LVS_EX_FULLROWSELECT | LVS_EX_GRIDLINES | LVS_EX_ONECLICKACTIVATE | LVS_EX_UNDERLINEHOT | LVS_EX_INFOTIP); m_listLang.DeleteAllItems(); LV_ITEM lvi; ZeroMemory(&lvi, sizeof(LV_ITEM)); lvi.iItem = m_listLang.InsertItem(LVIF_TEXT | LVIF_IMAGE, m_listLang.GetItemCount(), _T("English"), 0, 0, 1, NULL); CString strTemp; strTemp = PWM_VERSION_STR; lvi.iSubItem = 1; lvi.mask = LVIF_TEXT; lvi.pszText = (LPTSTR)(LPCTSTR)strTemp; m_listLang.SetItem(&lvi); strTemp = PWMX_ENGLISH_AUTHOR; lvi.iSubItem = 2; lvi.mask = LVIF_TEXT; lvi.pszText = (LPTSTR)(LPCTSTR)strTemp; m_listLang.SetItem(&lvi); strTemp = PWMX_ENGLISH_CONTACT; lvi.iSubItem = 3; lvi.mask = LVIF_TEXT; lvi.pszText = (LPTSTR)(LPCTSTR)strTemp; m_listLang.SetItem(&lvi); strTemp = TRL("Built-in"); lvi.iSubItem = 4; lvi.mask = LVIF_TEXT; lvi.pszText = (LPTSTR)(LPCTSTR)strTemp; m_listLang.SetItem(&lvi); const std_string strActive = GetCurrentTranslationTable(); std_string strFilter = SU_DriveLetterToUpper(Executable::instance().getPathOnly()); strFilter += PWM_DIR_LANGUAGES; strFilter += _T("\\*.lng"); CFileFind ff; BOOL bMore = ff.FindFile(strFilter.c_str(), 0); while(bMore != FALSE) { bMore = ff.FindNextFile(); // Ignore KeePass 2.x LNGX files (these are found even though // "*.lng" is specified as file mask) CString strFileName = ff.GetFileName(); strFileName = strFileName.MakeLower(); if((strFileName.GetLength() >= 5) && (strFileName.Right(5) == _T(".lngx"))) continue; CString strID = ff.GetFileTitle(); strID = strID.MakeLower(); if((strID != _T("standard")) && (strID != _T("english"))) { VERIFY(LoadTranslationTable((LPCTSTR)ff.GetFileTitle())); strTemp = (LPCTSTR)ff.GetFileTitle(); // strTemp += _T(" - "); // Name is used as identifier // strTemp += TRL("~LANGUAGENAME"); lvi.iItem = m_listLang.InsertItem(LVIF_TEXT | LVIF_IMAGE, m_listLang.GetItemCount(), strTemp, 0, 0, 1, NULL); strTemp = TRL("~LANGUAGEVERSION"); if(strTemp == _T("~LANGUAGEVERSION")) strTemp.Empty(); lvi.iSubItem = 1; lvi.mask = LVIF_TEXT; lvi.pszText = (LPTSTR)(LPCTSTR)strTemp; m_listLang.SetItem(&lvi); strTemp = TRL("~LANGUAGEAUTHOR"); if(strTemp == _T("~LANGUAGEAUTHOR")) strTemp.Empty(); lvi.iSubItem = 2; lvi.mask = LVIF_TEXT; lvi.pszText = (LPTSTR)(LPCTSTR)strTemp; m_listLang.SetItem(&lvi); strTemp = TRL("~LANGUAGEAUTHOREMAIL"); if(strTemp == _T("~LANGUAGEAUTHOREMAIL")) strTemp.Empty(); lvi.iSubItem = 3; lvi.mask = LVIF_TEXT; lvi.pszText = (LPTSTR)(LPCTSTR)strTemp; m_listLang.SetItem(&lvi); strTemp = ff.GetFilePath(); lvi.iSubItem = 4; lvi.mask = LVIF_TEXT; lvi.pszText = (LPTSTR)(LPCTSTR)strTemp; m_listLang.SetItem(&lvi); } } ff.Close(); VERIFY(LoadTranslationTable(strActive.c_str())); return TRUE; }
// initPlugsTab int CDataSourcesManager::initPlugsTab(LPCTSTR plugins_dir_path) { int i = 0; BOOL Found; CFileFind FList; // seznam nalezenych DLL // nalezeni vsech zasuvek a vyplneni jejich nazvu do pole PlugsTab CString Path = plugins_dir_path; Path += "\\*.dll"; Found = FList.FindFile(Path); while (Found) { Found = FList.FindNextFile(); // kody - odstraneni ".dll" z nazvu pluginu CString PluginName = FList.GetFileName(); PluginName.Replace(_T(".dll"), _T("")); PlugsTab.Add(CPluginRec(PluginName)); i++; } // inicializace vsech zasuvek pSockIfaceFn_t pInitFn; CString LibName; for(int j=0; j<=PlugsTab.GetUpperBound(); j++) { pInitFn = NULL; // ukazatel na inicializacni funkci zasuvky LibName.Format("%s\\%s", plugins_dir_path ,PlugsTab[j].PluginName); try { HMODULE m; PlugsTab[j].hLib = m = LoadLibrary(LibName); /******** //vypis chybove hlasky if (m== NULL) { DWORD n; LPVOID lpMsgBuf; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, n = GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language (LPTSTR) &lpMsgBuf, 0, NULL ); // Process any inserts in lpMsgBuf. // ... // Display the string. MessageBox( NULL, (LPCTSTR)lpMsgBuf, PlugsTab[j].PluginName, MB_OK | MB_ICONINFORMATION ); // Free the buffer. LocalFree( lpMsgBuf ); } /******/ } catch (...) { PlugsTab[j].hLib = NULL; } if(PlugsTab[j].hLib != NULL) { // ziskani adresy rozhrani pInitFn = (pSockIfaceFn_t) GetProcAddress(PlugsTab[j].hLib, _SOCK_IFACE_FN_NAME); if(pInitFn != NULL) // byla nalezena inicializacni funkce knihovny { // volani inicializacni funkce a nastaveni SockInterface try { PlugsTab[j].SockInterface = pInitFn(); } catch (...) { ::MessageBox(NULL, "Varovani: pri nacitani zasuvky doslo k vyjimce.\n\nprikaz: PlugsTab[j].SockInterface = pInitFn();", PlugsTab[j].PluginName, MB_ICONWARNING); } } } } return i; }
////////////////////////////////////////////////////////////////////////// //截获异常信息,并生成自定义的异常报告和弹出窗口 ////////////////////////////////////////////////////////////////////////// LONG WINAPI CustomExceptionFun(struct _EXCEPTION_POINTERS* ExceptionInfo) { SetUnhandledExceptionFilter(NULL); CString logPath,folderPath,errDetail; CString tips; CString strDes,strStack; CTime timer; CStdioFile stFile; TCHAR sz_module[MAX_PATH] = {0}; UINT_PTR section = 0, offset = 0; strDes.Format(L"%s\r\n%s",L"我们很抱歉地通知您,程序遇到错误,不得不终止。",L"以下是该错误的详细信息:"); //werDlg.SetDes(strDes); TCHAR szFileName[MAX_PATH]; ::GetModuleFileName(NULL, szFileName, MAX_PATH); *(_tcsrchr(szFileName, _T('\\')) + 1) = 0; timer = CTime::GetCurrentTime(); folderPath.Format(L"%slog\\",szFileName); logPath.Format(L"%slog\\dump_%d_%d_%d_%d.txt", szFileName, timer.GetYear(), timer.GetMonth(), timer.GetDay(), timer.GetHour()); tips.Format(L"%s\r\n%s",L"以上错误信息保存在:",logPath); g_strErrLogPath = logPath; //生成错误地址 get_logical_address(ExceptionInfo->ExceptionRecord->ExceptionAddress, sz_module, sizeof(sz_module)); //生成堆栈信息 stack_walk(strStack,ExceptionInfo->ContextRecord); //生成寄存器信息 #ifdef _M_IX86 // Intel Only! CString strReg; strReg = L"\nRegisters:\r\n"; strReg.Format(L"%sEAX:%08X\r\nEBX:%08X\r\nECX:%08X\r\nEDX:%08X\r\nESI:%08X\r\nEDI:%08X\r\n", strReg,ExceptionInfo->ContextRecord->Eax, ExceptionInfo->ContextRecord->Ebx, ExceptionInfo->ContextRecord->Ecx, ExceptionInfo->ContextRecord->Edx, ExceptionInfo->ContextRecord->Esi, ExceptionInfo->ContextRecord->Edi ); strReg.Format(L"%sCS:EIP: %04X:%08X\r\n",strReg, ExceptionInfo->ContextRecord->SegCs, ExceptionInfo->ContextRecord->Eip); strReg.Format(L"%sSS:ESP: %04X:%08X \r\nEBP:%08X\r\n",strReg, ExceptionInfo->ContextRecord->SegSs, ExceptionInfo->ContextRecord->Esp, ExceptionInfo->ContextRecord->Ebp ); strReg.Format(L"%sDS:%04X ES:%04X FS:%04X GS:%04X\r\n", strReg,ExceptionInfo->ContextRecord->SegDs, ExceptionInfo->ContextRecord->SegEs, ExceptionInfo->ContextRecord->SegFs, ExceptionInfo->ContextRecord->SegGs ); strReg.Format(L"%sFlags:%08X\r\n",strReg, ExceptionInfo->ContextRecord->EFlags); #endif //_M_IX86 //生成错误详细信息 errDetail.Format(L"Error Code:%x\r\n%s\r\nAddress:%x\r\n%s\r\n\r\n%s\r\n%s", ExceptionInfo->ExceptionRecord->ExceptionCode, get_exception_string(ExceptionInfo->ExceptionRecord->ExceptionCode), ExceptionInfo->ExceptionRecord->ExceptionAddress, sz_module, strReg, strStack); g_strErrDetail = errDetail; //写日志 CFileFind fileFinder; if (!fileFinder.FindFile(folderPath)) { if (::CreateDirectory(folderPath,NULL) < 0) return EXCEPTION_EXECUTE_HANDLER; } if (stFile.Open(logPath,CFile::modeCreate | CFile::modeNoTruncate | CFile::modeReadWrite | CFile::typeBinary)) { stFile.SeekToEnd(); stFile.Write("\377\376", 2); stFile.WriteString(errDetail); stFile.Close(); } //werDlg.DoModal(); CreateWerWindow(logPath,errDetail); return EXCEPTION_EXECUTE_HANDLER; }
//---------------------------------------------------------------------------- int CSTATImageVerify::EnableVerification(int fudge) { // temp variable FILETIME creationtime; creationtime.dwLowDateTime = 0; creationtime.dwHighDateTime = 0; // initialise settings iImageCount = 0; lastrefimageloaded = 0; margin = fudge; // check limits if (margin < 0) margin = 0; if (margin > 100) margin = 100; // populate our array with images CFileFind refimagefinder; if (refimagefinder.FindFile(referenceimagedir + _T("\\*.bmp"), 0)) { int i = 0; int iMoreFiles = true; for (i=0;i<VERIFY_MAX_IMAGES;i++) { if (iMoreFiles) { iMoreFiles = refimagefinder.FindNextFile(); refimagearray[i].completefilenamepath = refimagefinder.GetFilePath(); //store filename into array string variable refimagefinder.GetLastWriteTime(&creationtime); //store corresponding modification time refimagearray[i].lCreationTime = (((ULONGLONG) creationtime.dwHighDateTime) << 32) + creationtime.dwLowDateTime; iImageCount++; } else { refimagearray[i].completefilenamepath = _T(""); refimagearray[i].lCreationTime = 0; } } refimagefinder.Close(); } // now sort into date/time order if (iImageCount) { CSTATReferenceImages temp; bool bNotFinished = true; int i = 0; while (bNotFinished) { bNotFinished = false; for (i=0;i<iImageCount;i++) { if ((i + 1) < iImageCount && refimagearray[i+1].lCreationTime < refimagearray[i].lCreationTime) { temp = refimagearray[i]; refimagearray[i]= refimagearray[i+1]; refimagearray[i+1]= temp; bNotFinished = true; } } } } return iImageCount; }
BOOL UTIL::doesFileExist(const CString& strFilePath) { CFileFind ff; return ff.FindFile(strFilePath); }
void CDBManagePageFake::OnBnClickedButtonOpendatapackageFake() { // TODO: 在此添加控件通知处理程序代码 BROWSEINFO bi; char Buffer[MAX_PATH]; //CString m_DatasetFoldPath ;//将路径保存在一个CString对象里 bi.hwndOwner = this->m_hWnd; bi.pidlRoot =NULL;//初始化制定的root目录很不容易 bi.pszDisplayName =(LPWSTR)Buffer;//此参数如为NULL则不能显示对话框 bi.lpszTitle = L"选择光谱数据集文件夹路径"; bi.ulFlags =BIF_USENEWUI ; //BIF_EDITBOX;//带编辑框的风格 bi.lpfn = NULL; bi.lParam = 0; bi.iImage=IDR_MAINFRAME; //初始化入口参数bi结束 LPITEMIDLIST pIDList = SHBrowseForFolder(&bi);//调用显示选择对话框 if(pIDList==NULL) { return; } SHGetPathFromIDList(pIDList,(LPWSTR)Buffer); //取得文件夹路径到Buffer里 m_SpecDataFoldPath.Format(L"%s",Buffer); // free memory used IMalloc * imalloc = 0; if (SUCCEEDED(SHGetMalloc(&imalloc))) { imalloc->Free (pIDList); imalloc->Release(); } //从文件夹中导入光谱数据及相关信息 CString strDir=m_SpecDataFoldPath; strDir.Replace(L"\\",L"\\\\"); strDir += "\\*.*"; // 遍历得到所有子文件夹名 CFileFind finder; BOOL bWorking = finder.FindFile(strDir); //清空之前导入的数据集 OnBnClickedButtonClearspectoaddFake(); while (bWorking) { bWorking = finder.FindNextFile(); CString str=finder.GetFileName(); if(str.Right(4)==L".CSV"||str.Right(4)==L".csv" &&L"." !=str &&L".." != str)//注意该句需要排除“.”“..” { CString filename; CString fileTitle; //CString str=finder.GetFileName(); m_ary_SpecFilePath.Add(finder.GetFilePath()); //获取文件名(不包含后缀) //采用CString的Left(int count)截取CString中从左往右数的count个字符 //fileName.GetLength()-4中的4表示".csv"四个字符 m_ary_SpecFileName.Add(finder.GetFileTitle());//将文件名(不包含后缀)添加到数组中 } if(str.Right(4)==L".jpg" ||str.Right(4)==L".bmp"||str.Right(4)==L".gif"&&L"." !=str &&L".." != str) { m_ary_PicturesName.Add(finder.GetFileName()); m_ary_PicturesPath.Add(finder.GetFilePath()); } if(str==L"数据说明.xls"||str==L"数据说明.xlsx"&&L"." !=str &&L".." != str)m_ExcelInfoPath=finder.GetFilePath(); } finder.Close(); if(m_ary_SpecFileName.GetCount()==0) { MessageBox(L"该文件夹中没有规定格式的光谱数据,请重新选择!",L"警告",MB_ICONWARNING); return; } if(m_ary_SpecFileName.GetCount()<20) { MessageBox(L"光谱数量太少",L"警告",MB_ICONWARNING); return; } if(!m_ExcelInfoPath.IsEmpty()) { CString strDirExcel=m_ExcelInfoPath; CExcelOperator ExcelOperator; ExcelOperator.LoadExcel(strDirExcel); ExcelOperator.GetItem(1,1,L"String",m_WineName); ExcelOperator.ReleaseExcel(); } m_PicIndex=0; CString Winename; CString Wineinfo=L""; CString Comfrom; CString ReceiveDate; CString Wineinfotemp; SortCArrayByFirst(m_ary_SpecFileName,m_ary_SpecFilePath); for(int i=0;i<m_ary_SpecFileName.GetCount();i++) { CString NuMber; NuMber.Format(L"%d",i+1); m_ListSpectrumToAdd.InsertItem(i,NuMber); m_ListSpectrumToAdd.SetItemText(i,1,m_ary_SpecFileName[i]); m_ListSpectrumToAdd.SetItemText(i,2,m_WineName); } OnPaint(); }
void CAviHelper::BMPtoAVI(const wstring& szAVIName, const wstring& strBDir) { CFileFind finder; CString strBmpDir; strBmpDir.Format(_T("%s\\*.*"), strBDir.c_str()); AVIFileInit(); AVISTREAMINFO strhdr; PAVIFILE pfile; PAVISTREAM ps; int nFrames =0; HRESULT hr; BOOL bFind = finder.FindFile(strBmpDir); while(bFind) { bFind = finder.FindNextFile(); if(!finder.IsDots() && !finder.IsDirectory()) { CString str = finder.GetFilePath(); FILE *fp = _tfopen(str, _T("rb")); BITMAPFILEHEADER bmpFileHdr; BITMAPINFOHEADER bmpInfoHdr; fseek( fp,0,SEEK_SET); fread(&bmpFileHdr,sizeof(BITMAPFILEHEADER),1, fp); fread(&bmpInfoHdr,sizeof(BITMAPINFOHEADER),1, fp); BYTE *tmp_buf = NULL; if(nFrames ==0 ) { AVIFileOpen(&pfile, WS2S(szAVIName).c_str(), OF_WRITE | OF_CREATE,NULL); memset(&strhdr, 0, sizeof(strhdr)); strhdr.fccType = streamtypeVIDEO;// stream type strhdr.fccHandler = 0; strhdr.dwScale = 1; strhdr.dwRate = 15; // 15 fps strhdr.dwSuggestedBufferSize = bmpInfoHdr.biSizeImage ; SetRect(&strhdr.rcFrame, 0, 0, bmpInfoHdr.biWidth, bmpInfoHdr.biHeight); // And create the stream; hr = AVIFileCreateStream(pfile,&ps,&strhdr); // hr = AVIStreamSetFormat(ps,nFrames,&bmpInfoHdr,sizeof(bmpInfoHdr)); } tmp_buf = new BYTE[bmpInfoHdr.biWidth * bmpInfoHdr.biHeight * 3]; fread(tmp_buf, 1, bmpInfoHdr.biWidth * bmpInfoHdr.biHeight * 3, fp); hr = AVIStreamSetFormat(ps,nFrames,&bmpInfoHdr,sizeof(bmpInfoHdr)); hr = AVIStreamWrite(ps, // stream pointer nFrames , // time of this frame 1, // number to write (LPBYTE) tmp_buf, bmpInfoHdr.biSizeImage , // size of this frame AVIIF_KEYFRAME, // flags.... NULL, NULL); nFrames ++; fclose(fp); } } AVIStreamClose(ps); if(pfile != NULL) AVIFileRelease(pfile); AVIFileExit(); }
bool DeviceProxy::SendCashDataProc() { if (!m_sendCash.IsOpened()) return false; m_sendCash.SetTimeout(8000); CashInfo cashInfo; CString fileName; CString filePath; CFileFind ff; CString dataDir = ConfigBlock::GetInstance()->GetStringParameter(L"RunCashPara", L"dataPath", L"");; if (dataDir.Right(1) != "\\") dataDir += "\\"; dataDir += "*.raw"; //CString date, time, title, side; bool ret = ff.FindFile(dataDir); SendStartRunCashSignal(); while (ret) { ret = ff.FindNextFile(); if (ff.IsDirectory()) continue; if (!(fileName = ff.GetFileTitle())) continue; // 解析文件名 int index = 0; CString temp = L""; for (int i = 0;; i++) { if (fileName[i] != '_'&&i < fileName.GetLength()) temp += fileName[i]; else if (fileName[i] == '_' || i == fileName.GetLength()) { index++; switch (index) { //case 1: //date = temp; //break; //case 2: //time = temp; //break; case 3: swscanf_s(temp, _T("%d"), &(cashInfo.count)); break; case 4: //error = temp; swscanf_s(temp.Mid(3), _T("%d"), &(cashInfo.error)); break; case 5: //lasterr = temp; break; case 6: //den = temp; swscanf_s(temp.Mid(3), _T("%d"), &(cashInfo.denomination)); break; case 7: //dir = temp; swscanf_s(temp.Mid(3), _T("%d"), &(cashInfo.direction)); break; case 8: //ver = temp; swscanf_s(temp.Mid(3), _T("%d"), &(cashInfo.version)); break; case 9: //sn = temp; WideCharToMultiByte(CP_ACP, 0, temp, -1, cashInfo.sn, WideCharToMultiByte(CP_ACP, 0, temp, -1, NULL, 0, NULL, NULL), NULL, NULL); break; //case 10: // title = temp; // break; //case 11: // side = temp; // break; default: break; } temp = L""; if (index == 9) break; if (i == fileName.GetLength()) break; } } m_cashCnt++; filePath = ff.GetFilePath(); SendADCData(filePath); filePath = filePath.Left(filePath.Find(_T("adc"))); filePath += "cis_top.bmp"; SendCISData(filePath); SendCashInfo(cashInfo); } SendStopRunCashSignal(); PostMessage(AfxGetApp()->GetMainWnd()->GetSafeHwnd(), WM_RUN_CASH_STOPPED, 0, 1); }
BSTR CCMSInterfaceCtrl::doGetPathFiles( BSTR path_name) { USES_CONVERSION; Value root; FastWriter fw; string retStr; CString pattern(path_name); pattern+=L"\\*.*"; //CMSBOXW(pattern); Value images; int dir_index=0; int image_index=0; CString res; if(NULL!=path_name&&_file_exists(W2A(path_name))==0) { SetCurrentDirectory(path_name); CFileFind cff; BOOL found=cff.FindFile(pattern); while(found) { found=cff.FindNextFile(); //res+=L" "+cff.GetFilePath(); if(cff.IsDirectory()&&!cff.IsDots()){ CString full_path=cff.GetFilePath(); //full_path.Append(cff.GetFileName()); if(!full_path.IsEmpty()) { //res+=L"--"+full_path+L"--"; char *file=W2A(full_path.AllocSysString()); if(NULL!=file) { char buff[128]={0}; _itoa_s(dir_index++,buff,128,10); root[buff]=file; } } } if(cff.GetFileName().Find(L".jpg")>0|| cff.GetFileName().Find(L".gif")>0|| cff.GetFileName().Find(L".png")>0) { /* CMSBOX("image"); return NULL;*/ //CMSBOXW(cff.GetFilePath()); char l_buff[128]={0}; _itoa_s(image_index++,l_buff,128,10); images[l_buff]=W2A(cff.GetFilePath()); } } cff.Close(); } if(images.size()>=1) { root["images"]=images; } retStr=fw.write(root); //CMSBOXW(res); if(retStr.length()>0) { return SysAllocString(A2W(retStr.c_str())); } return CString("1").AllocSysString(); }
BOOL CCANMonitorApp::InitInstance() { // Begin of Multiple Language support if ( CMultiLanguage::m_nLocales <= 0 ) // Not detected yet { CMultiLanguage::DetectLangID(); // Detect language as user locale CMultiLanguage::DetectUILanguage(); // Detect language in MUI OS } TCHAR szModuleFileName[MAX_PATH]; // Get Module File Name and path int ret = ::GetModuleFileName(theApp.m_hInstance, szModuleFileName, MAX_PATH); if ( ret == 0 || ret == MAX_PATH ) { ASSERT(false); } // Load resource-only language DLL. It will use the languages // detected above, take first available language, // or you can specify another language as second parameter to // LoadLangResourceDLL. And try that first. ghLangInst = CMultiLanguage::LoadLangResourceDLL( szModuleFileName ); if (ghLangInst) { AfxSetResourceHandle( ghLangInst ); } // End of Multiple Language support INITCOMMONCONTROLSEX InitCtrls; InitCtrls.dwSize = sizeof(InitCtrls); InitCtrls.dwICC = ICC_WIN95_CLASSES; InitCommonControlsEx(&InitCtrls); //InitCommonControls(); // START CHANGES MADE FOR AUTOMATION CWinAppEx::InitInstance(); // Initialize OLE libraries if (!AfxOleInit()) { AfxMessageBox(_("Fail to Intilaize OLE")); return FALSE; } //CoInitializeEx(nullptr, COINIT_MULTITHREADED ); CBusmasterDump dump("BUSMASTER"); // END CHANGES MADE FOR AUTOMATION // Enable OLE/ActiveX objects support AfxEnableControlContainer(); InitContextMenuManager(); InitKeyboardManager(); InitTooltipManager(); CMFCToolTipInfo ttParams; ttParams.m_bVislManagerTheme = TRUE; theApp.GetTooltipManager()->SetTooltipParams(AFX_TOOLTIP_TYPE_ALL, RUNTIME_CLASS(CMFCToolTipCtrl), &ttParams); // Standard initialization // If you are not using these features and wish to reduce the size // of your final executable, you should remove from the following // the specific initialization routines you do not need. DEBUG //#ifdef _AFXDLL // Enable3dControls(); // Call this when using MFC in a shared DLL //#else // Enable3dControlsStatic(); // Call this when linking to MFC statically //#endif // Change the registry key under which our settings are stored. // TODO: You should modify this string to be something appropriate // such as the name of your company or organization. SetRegistryKey("RBEI-ETAS\\BUSMASTER_v3.1.0"); // START CHANGES MADE FOR AUTOMATION COleTemplateServer::RegisterAll(); // END CHANGES MADE FOR AUTOMATION //LoadStdProfileSettings(0); // Load standard INI file options (including MRU) // Enable drag/drop open // Enable DDE Execute open //EnableShellOpen(); //RegisterShellFileTypes(TRUE); // Display splash screen CCommandLineInfo cmdInfo; ParseCommandLine(cmdInfo); short shRegServer = -1; short shUnRegServer = -1; if (__argc > 1) { shRegServer = (short) strcmpi(__targv[1],"/regserver"); shUnRegServer = (short) strcmpi(__targv[1],"/unregserver"); } // Don't display a new MDI child window during startup if (cmdInfo.m_nShellCommand == CCommandLineInfo::FileNew || cmdInfo.m_nShellCommand == CCommandLineInfo::FileOpen) { cmdInfo.m_nShellCommand = CCommandLineInfo::FileNothing; } // START CHANGES MADE FOR AUTOMATION if (cmdInfo.m_bRunEmbedded || cmdInfo.m_bRunAutomated) { m_bFromAutomation = TRUE; // return TRUE; } else if (cmdInfo.m_nShellCommand == CCommandLineInfo::AppUnregister) { AfxOleUnregisterTypeLib(LIBID_CAN_MonitorApp); } else { COleObjectFactory::UpdateRegistryAll(); AfxOleRegisterTypeLib(AfxGetInstanceHandle(), LIBID_CAN_MonitorApp); } if ( shRegServer == 0 || shUnRegServer == 0 ) //If command line argument match { return FALSE; } if (!m_bFromAutomation) { CSplashScreen::ActivateSplashScreen(cmdInfo.m_bShowSplash); } // Allocate memory for CFlags m_pouFlags = &(CFlags::ouGetFlagObj()); // create main MDI Frame window CMainFrame* pMainFrame = new CMainFrame; if ( pMainFrame == nullptr ) { ::PostQuitMessage(0); return FALSE; } if (!pMainFrame->LoadFrame(IDR_MAINFRAME)) { return FALSE; } m_pMainWnd = pMainFrame; // Dispatch commands specified on the command line if (!ProcessShellCommand(cmdInfo)) { return FALSE; } m_pMainWnd->DragAcceptFiles(); // show main frame m_pMainWnd->ShowWindow(m_nCmdShow); m_pMainWnd->UpdateWindow(); //// Create message window if(m_pouMsgSgInactive == nullptr ) { if(m_bFromAutomation==FALSE) MessageBox(nullptr,_(MSG_MEMORY_CONSTRAINT), "BUSMASTER", MB_OK|MB_ICONINFORMATION); ::PostQuitMessage(0); } BOOL bResult; bResult = m_aomState[UI_THREAD].SetEvent(); // get the information of the last used configuration file.. // initialize the flag that indicates if the configuratin file has been // loaded.. m_bIsConfigFileLoaded = FALSE; CString ostrCfgFilename = ""; // If user has double click the .cfg file then assign that file name else // read from registry. if(cmdInfo.m_strFileName.IsEmpty() == TRUE) { //ostrCfgFilename = // GetProfileString(_(SECTION), defCONFIGFILENAME, ""); DWORD dwVal; bReadFromRegistry(HKEY_CURRENT_USER, _(SECTION), defCONFIGFILENAME, REG_SZ, ostrCfgFilename, dwVal); } else { ostrCfgFilename = cmdInfo.m_strFileName; } BOOL bValidDir = TRUE; CFileFind findFile; if (!ostrCfgFilename.IsEmpty() && !findFile.FindFile(ostrCfgFilename)) { DWORD dwErr = GetLastError(); CString strMsg = ""; if (dwErr == ERROR_PATH_NOT_FOUND) { bValidDir = FALSE; FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, nullptr, dwErr, 0, strMsg.GetBuffer(1024), 1024, nullptr); AfxMessageBox(strMsg); } } if(ostrCfgFilename.IsEmpty() == FALSE && bValidDir == TRUE) { bInitialiseConfiguration(m_bFromAutomation); // load the configuration information if(pMainFrame->nLoadConfigFile(ostrCfgFilename) != defCONFIG_FILE_SUCCESS) { //m_oConfigDetails.vInitDefaultValues(); m_ostrConfigFilename = ""; } else { m_ostrConfigFilename = ostrCfgFilename; } m_bIsConfigFileLoaded = TRUE; //build all nodes -- Node Simulation. pMainFrame->BuildAllNodes(); } else { BOOL bReturn = bInitialiseConfiguration(m_bFromAutomation); if(bReturn == FALSE ) { ::PostQuitMessage(0); } // Load a default database file //CStringArray omDatabaseArray; //CString omSampleDatabasePath; //omSampleDatabasePath.Format("%s\\Samples\\SampleDB.dbf",m_acApplicationDirectory); //DWORD dRetVal = pMainFrame->dLoadDataBaseFile(omSampleDatabasePath, FALSE); //if (dRetVal == S_OK) //{ // //omDatabaseArray.Add(omSampleDatabasePath); // //Store in configdetails // //bSetData(DATABASE_FILE_NAME, &omDatabaseArray); // bWriteIntoTraceWnd(_(MSG_DEFAULT_DATABASE)); // bWriteIntoTraceWnd(_(MSG_CREATE_UNLOAD_DATABASE)); //} pMainFrame->OnHex_DecButon(); // setting HEX by default } // ******** Filter workaround ******** // Filter list is initialised before msg wnd creation. So update display // filter here // Update Message Display Filter List //::PostThreadMessage(GUI_dwThread_MsgDisp, TM_UPDATE_FILTERLIST, nullptr, nullptr ); // ******** Filter workaround ******** // Start Logging if is enabled // Get the Flag Pointer CFlags* pomFlag = pouGetFlagsPtr(); if( pomFlag != nullptr ) { // Get the Logging Status BOOL bLogON = pomFlag->nGetFlagStatus(LOGTOFILE); // If it is on then post a message to display thread to start logging if(bLogON == TRUE ) { // Start Logging //CLogManager::ouGetLogManager().vStartStopLogging( TRUE ); } } //pMainFrame->OnHex_DecButon(); // setting HEX by default //CExecuteManager::ouGetExecuteManager().vStartDllReadThread(); return TRUE; }
//This function was added to CGrandDataFile to recursively retrieve a list of *.BID files in //a directory. It reads the file header to populate the CList of tFileRecords that is converted to //a safe array used by ImportManager. This was flagrantly stolen from Kelly Michel and modified to //search for and read in *.BID files. hn 6/8/2005 // 5-Jul-2005 SFK Removed dead code for readability void CGrandDataFile::GetCompleteFileList( short FacilityID, CList<tFileRecord, tFileRecord> *pFileList, const CString& Directory, bool IncludeSubdirs) { USES_CONVERSION; CFileFind Finder; BOOL bWorking; CString FileName; tFileRecord FileRecord; CString DirWithFileMask; // 3-aug-2005 hn Think that extra \ is appended could cause problems, search // for a \\, then only append backslash when needed if (Directory.GetAt (Directory.GetLength()-1) == '\\') { DirWithFileMask.Format("%s*.*", Directory); } else DirWithFileMask.Format("%s\\*.*", Directory); bWorking = Finder.FindFile(DirWithFileMask); //If this is an "archive" directory, then skip it completely, and everything that may be underneath it. int StartSubDirName = Directory.ReverseFind('\\'); if(StartSubDirName != -1) { CString SubDirName = Directory.Mid(StartSubDirName + 1); if(SubDirName.CompareNoCase("Archive")) //If SubDirName is not Archive... { do { bWorking = Finder.FindNextFile(); if(!Finder.IsDots()) { if(Finder.IsDirectory() && IncludeSubdirs) { //Recurse. GetCompleteFileList(FacilityID, pFileList, Finder.GetFilePath(), IncludeSubdirs); } else //if(Finder.IsNormal()) { FileName = Finder.GetFileName(); CString Ext = FileName.Mid(FileName.GetLength() - 3, 3); if(!Ext.CompareNoCase("BID") || !Ext.CompareNoCase("BI0")) { //<<QA>> does this bstr get freed??? FileRecord.File.bstrVal = (Finder.GetFilePath()).AllocSysString(); //**************************************************************** //Open the file and get info on the data in the file. Load that //file data into the FileRecord structure. //**************************************************************** CString err; //If we are not able to read the *.BID header, we fail if (!ReadHeader (W2T(FileRecord.File.bstrVal),&err)) { if (mpFile) CloseDataFile(); } else //Otherwise, save the file date and station ID read. { SYSTEMTIME sysTime; COleDateTime fileDate = GetFileDate (); fileDate.GetAsSystemTime (sysTime); SystemTimeToVariantTime (&sysTime,&FileRecord.Date.date); FileRecord.StationID.lVal = (long) GetStationID (); pFileList->AddTail (FileRecord); CloseDataFile (); } } } } } while(bWorking != 0); } } }