//---------------------------------------------------------------------------
int SteemIntro()
{
	EasyStr caption=T("Welcome to Steem"),text;

  text=T("Thank you for running the Steem Engine. We hope you will get many hours of enjoyment from this program. Before you can start there's just a few things to set up.");
#ifdef WIN32
  int Ret;
  MSGBOXPARAMS mbp;
  mbp.cbSize=sizeof(MSGBOXPARAMS);
  mbp.hwndOwner=NULL;
  mbp.hInstance=Inst;
  mbp.dwContextHelpId=0;
  mbp.lpfnMsgBoxCallback=NULL;
  mbp.dwLanguageId=GetUserDefaultLangID();
  mbp.lpszIcon=RCNUM(RC_ICO_APP);

  text+=" ";
  text+=T("Do you want to put a shortcut to Steem in your Start Menu?");
  mbp.lpszCaption=caption;
  mbp.lpszText=text.Text;
  mbp.dwStyle=MB_USERICON | MB_YESNO;
  if (MessageBoxIndirect(&mbp)==IDYES){
    ITEMIDLIST *idl;
    if (SHGetSpecialFolderLocation(NULL,CSIDL_PROGRAMS,&idl)==NOERROR){
      IMalloc *Mal;SHGetMalloc(&Mal);
      EasyStr Path;Path.SetLength(MAX_PATH);
      SHGetPathFromIDList(idl,Path);
      Mal->Free(idl);

      EasyStr ThisExeName=GetEXEFileName();
      CreateDirectory(Path+"\\Steem Engine",NULL);
      CreateLink(Path+"\\Steem Engine\\Steem Engine.lnk",ThisExeName,"The STE Emulating Engine");
      CreateLink(Path+"\\Steem Engine\\Readme.lnk",RunDir+"\\readme.txt","Steem Engine Info");
    }
  }
#elif defined(UNIX)
  alert.set_icons(&Ico64,ICO64_STEEM,&Ico16,ICO16_STEEM);
  if (1==alert.ask(XD,text,caption,T("Continue")+"|"+T("Abort"),0,1)){
		return 1;
  }
#endif

  caption=T("TOS Image");
  text=T("The most important file Steem needs to run is an image of the ST operating system TOS. If you haven't got one you cannot run Steem. They are easily downloadable from the internet, probably from the same place that you downloaded Steem. Alternatively you can get ST programs that will save out the TOS from an ST. After clicking OK find a TOS image file and click open. This setting, and all the other settings you are about to set, can be easily changed at any time when running Steem.");
#ifdef WIN32
	mbp.lpszText=text;
	mbp.lpszCaption=caption;
  mbp.dwStyle=MB_USERICON | MB_OK;
  MessageBoxIndirect(&mbp);
#elif defined(UNIX)
	alert.ask(XD,text,caption,T("Okay"),0,0);
#endif
  LOOP{
#ifdef WIN32
    ROMFile=FileSelect(NULL,T("Select TOS Image"),RunDir,FSTypes(3,NULL),1,true,"img");
#elif defined(UNIX)
		fileselect.set_corner_icon(&Ico16,ICO16_CHIP);
    ROMFile=fileselect.choose(XD,RunDir,"",T("Select TOS Image"),FSM_LOAD | FSM_LOADMUSTEXIST,
    												romfile_parse_routine,".img");
#endif
    if (ROMFile.IsEmpty()) return 1;

    if (load_TOS(ROMFile)==0) break;

    MessageBox((WINDOWTYPE)0,ROMFile+" "+T("is not a valid TOS"),T("Error Loading OS"),
                MB_ICONEXCLAMATION | MB_TASKMODAL | MB_TOPMOST | MB_SETFOREGROUND);
  }


	caption=T("Disk Images");
  text=T("The next few settings regard the way Steem emulates disks. Steem, and all other ST emulators, use files with the extension ST, STT, DIM or MSA on a PC drive for its floppy disks. This is the format most things you download for the ST will be in. If you have some of these files already then you can tell Steem which folder they are in. This will become your home folder and makes it easy to switch disks in and out of drives. If you don't have any then select a suitable folder on your PC hard disk and Steem will create a blank disk for you there.")+"\n\n"+
         T("Click cancel if you'd rather set up the home folder later.");

	bool proceed;
#ifdef WIN32
  mbp.lpszCaption=caption;
  mbp.lpszText=text;
  mbp.dwStyle=MB_USERICON | MB_OKCANCEL;
  Ret=MessageBoxIndirect(&mbp);
  proceed=(Ret==IDOK);
#elif defined(UNIX)
	proceed=!alert.ask(XD,text,caption,T("Okay")+"|"+T("Cancel"),0,1);
#endif

  if (proceed){
  	EasyStr Path;
#ifdef WIN32
    Path=ChooseFolder(NULL,T("Pick a Folder"),RunDir);
    if (Path.Empty()) Path=RunDir;
#elif defined(UNIX)
		fileselect.set_corner_icon(&Ico16,ICO16_FOLDER);
	  Path=fileselect.choose(XD,RunDir,"",T("Pick a Folder"),
	    FSM_CHOOSE_FOLDER | FSM_CONFIRMCREATE,folder_parse_routine,"");
#endif
		if (Path.NotEmpty()){
      DiskMan.HomeFol=Path;
      NO_SLASH(DiskMan.HomeFol);
      DiskMan.DisksFol=DiskMan.HomeFol;

    	bool Found=0;
      {
	      DirSearch ds;
		    if (ds.Find(DiskMan.HomeFol+SLASH+"*.*")){
		    	do{
            if (FileIsDisk(ds.Name)){
							Found=true;
							break;
		    		}
		    	}while (ds.Next());
		    }
	    }

      if (Found==0){
        if (DiskMan.CreateDiskImage(DiskMan.HomeFol+SLASH+T("Blank Disk")+".st",
                                    80*9*2,9,2)){
          FloppyDrive[0].SetDisk(DiskMan.HomeFol+SLASH+T("Blank Disk")+".st");
          FloppyDrive[0].DiskName=T("Blank Disk");
          DiskMan.InsertHistoryAdd(0,FloppyDrive[0].DiskName,FloppyDrive[0].GetDisk(),"");
        }
      }
    }
  }

  caption=T("Hard Drives");
  text=T("Steem can also emulate hard drives on the ST. This isn't as reliable as disk images, but it works for most things. You can have up to 10 hard drives, each one is mapped to a folder on your PC hard drive.")+"\n\n"+
         T("Would you like to select a folder to be ST hard drive C now?");
 	proceed=false;
#ifdef WIN32
  mbp.lpszText=text;
  mbp.lpszCaption=caption;
  mbp.dwStyle=MB_USERICON | MB_YESNO;
  Ret=MessageBoxIndirect(&mbp);
  if (Ret==IDYES){
  	proceed=true;
  }
#elif defined(UNIX)
	proceed=!alert.ask(XD,text,caption,T("Yes")+"|"+T("No"),0,1);
#endif
	if (proceed){
    int Let=0;
    EasyStr Mess[9];
    Mess[0]=T("Would you like to select a folder to be ST hard drive D now?");
    Mess[1]=T("Would you like to select a folder to be ST hard drive E now?");
    Mess[2]=T("Would you like to select a folder to be ST hard drive F now?");
    Mess[3]=T("Would you like to select a folder to be ST hard drive G now?");
    Mess[4]=T("Would you like to select a folder to be ST hard drive H now?");
    Mess[5]=T("Would you like to select a folder to be ST hard drive I now?");
    Mess[6]=T("Would you like to select a folder to be ST hard drive J now?");
    Mess[7]=T("Would you like to select a folder to be ST hard drive K now?");
    Mess[8]=T("Would you like to select a folder to be ST hard drive L now?");
    EasyStr Path=RunDir;
#ifdef WIN32
    do{
      Path=ChooseFolder(NULL,T("Pick a Folder"),Path);
      if (Path.Empty()) break;
		  NO_SLASH(Path);

      if (Let>=9) break;
      HardDiskMan.NewDrive(Path);
      mbp.lpszText=Mess[Let++];
      mbp.dwStyle=MB_USERICON | MB_YESNO;
      Ret=MessageBoxIndirect(&mbp);
    }while (Ret==IDYES);
#elif defined(UNIX)
		fileselect.set_corner_icon(&Ico16,ICO16_HARDDRIVE);
		do{
		  Path=fileselect.choose(XD,RunDir,"",T("Pick a Folder"),
		    FSM_CHOOSE_FOLDER | FSM_CONFIRMCREATE,folder_parse_routine,"");
		  if (Path.Empty()) break;
		  NO_SLASH(Path);

      if (Let>=9) break;
      HardDiskMan.NewDrive(Path);
			proceed=!alert.ask(XD,Mess[Let++],caption,T("Yes")+"|"+T("No"),1,1);
		}while(proceed);
#endif
  }

	caption=T("Get Ready For Steem!");
	text=T("Congratulations, Steem is now ready to go. Click on the yellow play button to start emulation. To release the PC mouse press the Pause/Break key. To stop emulation click on the run button again or press Shift + Pause/Break.")+
         "\n\n"+T("Have fun!");

#ifdef WIN32
  mbp.lpszCaption=caption;
  mbp.lpszText=text;
  mbp.dwStyle=MB_USERICON | MB_OK;
  MessageBoxIndirect(&mbp);
  return 0;
#elif defined(UNIX)
	alert.ask(XD,text,caption,T("Okay"),0,0);
  return 0;
#endif
}
//将已经按照姓名汇总的数据分别输出到excel文件中
void CGhQuery::OnBnClickedClassifyExcel()
{
	// 添加文件保存目录

    CString str,strPath;
	
//    ZeroMemory(szPath, sizeof(szPath));   

    BROWSEINFO bi;   
    bi.hwndOwner = m_hWnd;   
    bi.pidlRoot = NULL;   
	bi.pszDisplayName = str.GetBuffer(MAX_PATH);   
    bi.lpszTitle = "请选择汇总信息存放目录:";   
    bi.ulFlags = 0;   
    bi.lpfn = NULL;   
    bi.lParam = 0;   
    bi.iImage = 0;   
    //弹出选择目录对话框
    LPITEMIDLIST lp = SHBrowseForFolder(&bi);   
	str.ReleaseBuffer();

	SHGetPathFromIDList(lp,strPath.GetBuffer(MAX_PATH)) ;
    strPath.ReleaseBuffer();
    
	if(strPath.GetLength() <3){
		AfxMessageBox("选择的目录无效,请重新选择可读写的目录....");
		return;
	}


	UpdateData();

	CFormGhList *pf=(CFormGhList*)theApp.pParentGrid.pGrid;
	int iRows=pf->m_grid.GetRowCount();
	int iCols=pf->m_grid.GetColumnCount();
	if( iRows < 3) {
		AfxMessageBox("没有数据需要进行分类汇总输出,请先进行数据分类汇总....");
		return;
	}
	int iType=m_Type.GetCurSel();
	CString strJournalType;
	if( iType == CB_ERR || iType == 1 )strJournalType="报刊合计";
	else m_Type.GetLBText(iType,strJournalType);

	CString strPath2;
	strPath2.Format("(%s)%s-%s",strJournalType,m_strStart,m_strEnd);
	if( strPath.Right(1) == '\\' )  //路径选择为根目录时,目录后会自动附加'\\'字符,如果是正常的目录,则没有附加的'\\',所以要进行判断
		strPath=strPath+strPath2;
	else 
		strPath=strPath+"\\"+strPath2;

	//判断目录是否存在    
	WIN32_FIND_DATA fd;  
    HANDLE hFind = FindFirstFile(strPath, &fd);  
   // BOOL bFilter = (FALSE == dwFilter) ? TRUE : fd.dwFileAttributes & dwFilter;  
   // BOOL RetValue = ((hFind != INVALID_HANDLE_VALUE) && bFilter) ? TRUE : FALSE;  

    FindClose(hFind);  
	if( fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
		{
			AfxMessageBox("当前目前下已存在要导出的文件目录,如需导出,请重新选择目录...");
			return;
	}
	


	if( ! CreateDirectory(strPath,NULL) ){
		AfxMessageBox("Create directory is error !!");
		return;
	}
	strPath+="\\";
	const int COL_FACTORY=1,COL_NAME=2,COL_PRICE=3,COL_SQ=0;

	_Application app2;
	Workbooks books2;
	_Workbook book2;
	Worksheets sheets2;
	_Worksheet sheet2;
	 COleVariant vOpt(DISP_E_PARAMNOTFOUND,VT_ERROR);
const int  IDC_PROGRESS_EXCEL=WM_USER+10003;
	CProgressEx pp;
	CRect r1(0,0,400,25);
	pp.Create(WS_CHILD |PBS_SMOOTH|WS_BORDER ,r1,AfxGetMainWnd()->GetForegroundWindow(),IDC_PROGRESS_EXCEL);
	pp.UpdateWindow();
	pp.ShowWindow(SW_SHOW);
	pp.CenterWindow();
	pp.Invalidate();
	pp.SetRange32(0,iRows );
	pp.strView="正在准备导出...请稍等!!";

	app2.CreateDispatch("excel.application");
	if(!app2){
		AfxMessageBox("请注意系统中必须装有EXCEL97 或者 EXCEL2000 ,否则此功能不能使用...");
		return;
	}
	CString strFileName;
	strFileName.Format("%sspec.xls",LoginInformation.path);
	books2=app2.GetWorkbooks();


	Range vRange;
	SQ_EXCEL9::Font font;
	long x,y;
	CString str1,str2;
	
	app2.SetVisible(false);
//	pp.strView="";
	books2=app2.GetWorkbooks(); //OPEN excel template
	book2=books2.Open(strFileName,vOpt,vOpt,vOpt,vOpt,vOpt,vOpt,vOpt,vOpt,vOpt,vOpt,vOpt,vOpt);
	sheets2=book2.GetWorksheets();
	sheet2=sheets2.GetItem(COleVariant((short)1));


	CString szFlgFactory,szTmp;
	CString szOutFile,szCell;
	int xlsRow(3),clrRow(0);	//clrRow记录文件最后一行行号
	for(int i=1; i< iRows ;i++)
	{
		szFlgFactory=pf->m_grid.GetItemText(i,COL_FACTORY);

		if( xlsRow ==3 ){			
			szCell="a1";
			vRange=sheet2.GetRange(_variant_t(szCell),_variant_t(szCell) );
			vRange.SetValue(_variant_t(szFlgFactory));
			szOutFile.Format("%s%s(%s-%s).xls",strPath,szFlgFactory,m_strStart,m_strEnd);
			if(  clrRow ){
				szCell.Format("A3:%c%d",'A'+COL_PRICE,clrRow+1);
				vRange=sheet2.GetRange(_variant_t(szCell),_variant_t(szCell) );
				szCell="";
				vRange.SetValue(_variant_t(szCell));
				clrRow=0;
			}
		}

		if( i !=1 && xlsRow!= 3 ){
	
			szTmp=pf->m_grid.GetItemText(i-1,COL_FACTORY);
			if( szTmp.Compare(szFlgFactory) !=0 ){
	
				szCell.Format("%c%d",'A'+COL_PRICE,xlsRow);
				vRange=sheet2.GetRange(_variant_t(szCell),_variant_t(szCell) );
				szCell.Format("=sum(D3:D%d)",xlsRow-1);
				vRange.SetValue(_variant_t(szCell));
			
				book2.SaveAs(_variant_t(szOutFile),vOpt,vOpt,vOpt,vOpt,vOpt,0L,vOpt,vOpt,vOpt,vOpt);
			
				xlsRow=3;
				i--;
				continue;
			}

		}
		for(int iCol=0; iCol< iCols ; iCol++){	//输出到excel表格
			szCell.Format("%c%d",'A'+iCol,xlsRow);
			vRange=sheet2.GetRange(_variant_t(szCell),_variant_t(szCell) );
			if( iCol == 0 ) szCell.Format("%d",xlsRow-2);   //xlsRow 起始行为3,第一列为序号列,
			else 	
				szCell=pf->m_grid.GetItemText(i,iCol);
			vRange.SetValue(_variant_t(szCell));
		}
		xlsRow++;
		clrRow=xlsRow;
	
		pp.strView.Format("%2.0f%%",double(i)/iRows*100);
		pp.SetPos(i);

	}

	pp.SendMessage(WM_CLOSE);

	sheet2.ReleaseDispatch();

	sheets2.ReleaseDispatch();

	book2.SetSaved(true);	//设置已存储标志,在quit是不提示更改保存
	book2.Close(_variant_t(false ),vOpt,vOpt);

	books2.Close();
	book2.ReleaseDispatch();
	books2.ReleaseDispatch();
	app2.Quit();
	app2.ReleaseDispatch();	
	
}
Exemple #3
0
int CBrowseFolder::BrowseCallBackProc(HWND hwnd, UINT uMsg, LPARAM lParam, LPARAM /*lpData*/)
{
	RECT ListViewRect,Dialog;
	//Initialization callback message
	if (uMsg == BFFM_INITIALIZED)
	{
		if (_tcslen(m_CheckText) > 0)
		{
			bool bSecondCheckbox = (_tcslen(m_CheckText2)!=0);
			//Rectangles for getting the positions
			checkbox = CreateWindowEx(	0,
				_T("BUTTON"),
				m_CheckText,
				WS_CHILD|WS_VISIBLE|WS_CLIPCHILDREN|BS_AUTOCHECKBOX,
				0,100,100,50,
				hwnd,
				0,
				NULL,
				NULL);
			if (checkbox == NULL)
				return 0;

			if (bSecondCheckbox)
			{
				//Rectangles for getting the positions
				checkbox2 = CreateWindowEx(	0,
					_T("BUTTON"),
					m_CheckText2,
					WS_CHILD|WS_VISIBLE|WS_CLIPCHILDREN|BS_AUTOCHECKBOX,
					0,100,100,50,
					hwnd,
					0,
					NULL,
					NULL);
				if (checkbox2 == NULL)
					return 0;
			}

			ListView = FindWindowEx(hwnd,NULL,_T("SysTreeView32"),NULL);
			if (ListView == NULL)
				ListView = FindWindowEx(hwnd,NULL,_T("SHBrowseForFolder ShellNameSpace Control"),NULL);

			if (ListView == NULL)
				return 0;

			//Gets the dimensions of the windows
			GetWindowRect(hwnd,&Dialog);
			GetWindowRect(ListView,&ListViewRect);
			POINT pt;
			pt.x = ListViewRect.left;
			pt.y = ListViewRect.top;
			ScreenToClient(hwnd, &pt);
			ListViewRect.top = pt.y;
			ListViewRect.left = pt.x;
			pt.x = ListViewRect.right;
			pt.y = ListViewRect.bottom;
			ScreenToClient(hwnd, &pt);
			ListViewRect.bottom = pt.y;
			ListViewRect.right = pt.x;
			//Sets the list view controls dimensions
			SetWindowPos(ListView,0,ListViewRect.left,
				bSecondCheckbox ? ListViewRect.top+40 : ListViewRect.top+20,
				(ListViewRect.right-ListViewRect.left),
				bSecondCheckbox ? (ListViewRect.bottom - ListViewRect.top)-40 : (ListViewRect.bottom - ListViewRect.top)-20,
				SWP_NOZORDER);
			//Sets the window positions of checkbox and dialog controls
			SetWindowPos(checkbox,HWND_BOTTOM,ListViewRect.left,
				ListViewRect.top,
				(ListViewRect.right-ListViewRect.left),
				14,
				SWP_NOZORDER);
			if (bSecondCheckbox)
			{
				SetWindowPos(checkbox2,HWND_BOTTOM,ListViewRect.left,
					ListViewRect.top+20,
					(ListViewRect.right-ListViewRect.left),
					14,
					SWP_NOZORDER);
			}
			HWND label = FindWindowEx(hwnd, NULL, _T("STATIC"), NULL);
			if (label)
			{
				HFONT hFont = (HFONT)::SendMessage(label, WM_GETFONT, 0, 0);
				LOGFONT lf = {0};
				GetObject(hFont, sizeof(lf), &lf);
				HFONT hf2 = CreateFontIndirect(&lf);
				::SendMessage(checkbox, WM_SETFONT, (WPARAM)hf2, TRUE);
				if (bSecondCheckbox)
					::SendMessage(checkbox2, WM_SETFONT, (WPARAM)hf2, TRUE);
			}
			else
			{
				//Sets the fonts of static controls
				SetFont(checkbox,_T("MS Sans Serif"),12);
				if (bSecondCheckbox)
					SetFont(checkbox2,_T("MS Sans Serif"),12);
			}

			// Subclass the checkbox control. 
			CBProc = (WNDPROC) SetWindowLongPtr(checkbox,GWLP_WNDPROC, (LONG_PTR) CheckBoxSubclassProc); 
			//Sets the checkbox to checked position
			SendMessage(checkbox,BM_SETCHECK,(WPARAM)m_bCheck,0);
			if (bSecondCheckbox)
			{
				CBProc = (WNDPROC) SetWindowLongPtr(checkbox2,GWLP_WNDPROC, (LONG_PTR) CheckBoxSubclassProc2); 
				SendMessage(checkbox2,BM_SETCHECK,(WPARAM)m_bCheck,0);
			}
			// send a resize message to the resized list view control. Otherwise it won't show
			// up properly until the user resizes the window!
			SendMessage(ListView, WM_SIZE, SIZE_RESTORED, MAKELONG(ListViewRect.right-ListViewRect.left, bSecondCheckbox ? (ListViewRect.bottom - ListViewRect.top)-40 : (ListViewRect.bottom - ListViewRect.top)-20));
		}
		
		// now set the default directory
		SendMessage(hwnd, BFFM_SETSELECTION, TRUE, (LPARAM)(LPCTSTR)m_sDefaultPath);
	}
	if (uMsg == BFFM_SELCHANGED)
	{
		// Set the status window to the currently selected path.
		TCHAR szDir[MAX_PATH];
		if (SHGetPathFromIDList((LPITEMIDLIST)lParam, szDir))
		{
			SendMessage(hwnd,BFFM_SETSTATUSTEXT, 0, (LPARAM)szDir);
		}
	}
	
	return 0;
}
Exemple #4
0
CXMLParser::CXMLParser(const std::string& fileStr)
{
#pragma region Create temp folder
	CString szFolder;
	LPITEMIDLIST pidl;
	LPMALLOC pShellMalloc;
	TCHAR szTemp[MAX_PATH];
	if(SUCCEEDED(SHGetMalloc(&pShellMalloc)))
	{
		if(SUCCEEDED(SHGetSpecialFolderLocation(NULL,
			CSIDL_APPDATA,&pidl)))
		{
			SHGetPathFromIDList(pidl,szTemp);
			szFolder =szTemp;
			pShellMalloc->Free(pidl);
		}
		pShellMalloc->Release();
	}

	szFolder.TrimRight(_T("\\"));
	szFolder += _T("\\TF3DXML");
	MyDeleteFile(szFolder);
	CFileStatus fstatus;
	if (!CFile::GetStatus(szFolder,fstatus))
	{
		::CreateDirectory(szFolder,NULL);
	}

#pragma endregion Create temp folder

	const size_t strsize=(szFolder.GetLength()+1)*2; // 宽字符的长度;
	char * qstr= new char[strsize]; //分配空间;
	size_t sz=0;
	wcstombs_s(&sz,qstr,strsize,szFolder,_TRUNCATE);

	cUnpackFile unpackTool;
	unpackTool.CreateDirFromZip(qstr,fileStr.c_str());
	delete []qstr;
	//delete []filestr;

	CFileFind finder;
	LPCTSTR pstr = szFolder;
	CString strWildcard(pstr);
	strWildcard += _T("\\*.*");
	CString m_ext_now;
	m_ext_now.Format(_T("%s"),_T("3DRep"));
	CString m_str_3dxml;	//查找装配树的.3dxml文件
	m_str_3dxml.Format(_T("%s"),_T("3dxml"));
	BOOL bWorking = finder.FindFile(strWildcard);
	while (bWorking)
	{
		bWorking = finder.FindNextFile();

		CString name = finder.GetFileName();
		CString extend = name.Right(name.GetLength() - name.ReverseFind('.') - 1);
		if(!finder.IsDots())
		{
			if (extend == m_ext_now)//m_ext_now为你要查找的文件扩展名
			{
				CString str=finder.GetFilePath();
				// 先得到要转换为字符的长度
				const size_t strsize=(str.GetLength()+1)*2; // 宽字符的长度;
				char * pstr= new char[strsize]; //分配空间;
				size_t sz=0;
				wcstombs_s(&sz,pstr,strsize,str,_TRUNCATE);

				TiXmlDocument *myDocument = new TiXmlDocument(pstr);
				myDocument->LoadFile();
				TiXmlElement *rootElement=myDocument->RootElement();
				if(rootElement->FirstChildElement()->FirstChildElement()!=NULL && strcmp(rootElement->FirstChildElement()->FirstChildElement()->Value(),"Rep")==0)
				{
					m_pTempFile=new TF3DRepFile();
					string filename;
					CT2A xx(name);
					filename = xx;
					m_pTempFile->SetFileName(filename);
					TraverseRep(rootElement->FirstChildElement()->FirstChildElement());
					m_fileList.push_back(m_pTempFile);
				}
				delete myDocument;
				delete []pstr;
			}
			if(extend == m_str_3dxml)
			{
				CString str=finder.GetFilePath();
				// 先得到要转换为字符的长度
				const size_t strsize=(str.GetLength()+1)*2; // 宽字符的长度;
				char * pstr= new char[strsize]; //分配空间;
				size_t sz=0;
				wcstombs_s(&sz,pstr,strsize,str,_TRUNCATE);

				TiXmlDocument *myDocument = new TiXmlDocument(pstr);
				myDocument->LoadFile();
				TiXmlElement *rootElement=myDocument->RootElement();
				if(strcmp(rootElement->FirstChildElement()->NextSiblingElement()->Value(),"ProductStructure")==0)
				{
					rootElement=rootElement->FirstChildElement()->NextSiblingElement()->FirstChildElement();
					m_root=new ReferenceTreeElement();
					m_root->value=(char *)rootElement->FirstAttribute()->Next()->Next()->Value();
					m_root->id=atoi(rootElement->FirstAttribute()->Next()->Value());
					m_root->instancename="";
					m_root->FirstChildElement=NULL;
					m_root->NextSimblingElement=NULL;
					while(rootElement!=NULL)
					{
						if(strcmp(rootElement->Value(),"Reference3D")==0)
						{
							AddReference3D(rootElement);
						}
						if(strcmp(rootElement->Value(),"Instance3D")==0)
						{
							AddInstance3D(rootElement);
						}
						rootElement=rootElement->NextSiblingElement();
					}
					FindAllTreeNode();
					ReferenceTreeElement *p=m_root;
					LinkTreeNode(p,NULL);
				}
			}
		}
	}

	finder.Close();

	MyDeleteFile(szFolder);
}
Exemple #5
0
void __declspec(dllexport) SelectFolderDialog(HWND hwndParent, int string_size, TCHAR *variables, stack_t **stacktop, extra_parameters *extra)
{
  BROWSEINFO bi;

  TCHAR result[MAX_PATH];
  TCHAR initial[MAX_PATH];
  TCHAR title[1024];
  LPITEMIDLIST resultPIDL;

  EXDLL_INIT();

  if (popstringn(title, sizeof(title)/sizeof(title[0])))
  {
    pushstring(_T("error"));
    return;
  }

  if (popstringn(initial, sizeof(initial)/sizeof(initial[0])))
  {
    pushstring(_T("error"));
    return;
  }

  bi.hwndOwner = hwndParent;
  bi.pidlRoot = NULL;
  bi.pszDisplayName = result;
  bi.lpszTitle = title;
#ifndef BIF_NEWDIALOGSTYLE
#define BIF_NEWDIALOGSTYLE 0x0040
#endif
  bi.ulFlags = BIF_STATUSTEXT | BIF_RETURNONLYFSDIRS | BIF_NEWDIALOGSTYLE;
  bi.lpfn = BrowseCallbackProc;
  bi.lParam = (LPARAM) initial;
  bi.iImage = 0;

  /*if (pField->pszRoot) {
    LPSHELLFOLDER sf;
    ULONG eaten;
    LPITEMIDLIST root;
    int ccRoot = (lstrlen(pField->pszRoot) * 2) + 2;
    LPWSTR pwszRoot = (LPWSTR) MALLOC(ccRoot);
    MultiByteToWideChar(CP_ACP, 0, pField->pszRoot, -1, pwszRoot, ccRoot);
    SHGetDesktopFolder(&sf);
    sf->ParseDisplayName(hConfigWindow, NULL, pwszRoot, &eaten, &root, NULL);
    bi.pidlRoot = root;
    sf->Release();
    FREE(pwszRoot);
  }*/

  resultPIDL = SHBrowseForFolder(&bi);
  if (!resultPIDL)
  {
    pushstring(_T("error"));
    return;
  }

  if (SHGetPathFromIDList(resultPIDL, result))
  {
    pushstring(result);
  }
  else
  {
    pushstring(_T("error"));
  }

  CoTaskMemFree(resultPIDL);
}
Exemple #6
0
void PATHMANAGER::Init(std::ostream & info_output, std::ostream & error_output)
{
	typedef std::vector<fs::path> Paths;

	// Set Ogre plugins dir
	{
		ogre_plugin_dir = "";
		char *plugindir = getenv("OGRE_PLUGIN_DIR");
		if (plugindir) {
			ogre_plugin_dir = plugindir;
		#ifndef _WIN32
		} else if (fs::exists(fs::path(OGRE_PLUGIN_DIR) / "RenderSystem_GL.so")) {
			ogre_plugin_dir = OGRE_PLUGIN_DIR;
		#endif
		} else {
			#ifdef _WIN32
			ogre_plugin_dir = ".";
			#else
			Paths dirs;
			#if defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(_M_X64)
			dirs.push_back("/usr/local/lib64");
			dirs.push_back("/usr/lib64");
			#else
			dirs.push_back("/usr/local/lib32");
			dirs.push_back("/usr/lib32");
			#endif
			dirs.push_back("/usr/local");
			dirs.push_back("/usr/lib");
			// Loop through the paths and pick the first one that contain a plugin
			for (Paths::const_iterator p = dirs.begin(); p != dirs.end(); ++p) {
				if (fs::exists(*p / "OGRE/RenderSystem_GL.so")) {
					ogre_plugin_dir = (*p / "OGRE").string();
					break;
				} else if (fs::exists(*p / "ogre/RenderSystem_GL.so")) {
					ogre_plugin_dir = (*p / "ogre").string();
					break;
				}
			}
			#endif
		}
	}

	fs::path shortDir = "stuntrally";
	// Figure out the user's home directory
	{
		home_dir = "";
		#ifndef _WIN32 // POSIX
			char *homedir = getenv("HOME");
			if (homedir == NULL)
			{
				home_dir = "/home/";
				homedir = getenv("USER");
				if (homedir == NULL) {
					homedir = getenv("USERNAME");
					if (homedir == NULL) {
						error_output << "Could not find user's home directory!" << std::endl;
						home_dir = "/tmp/";
					}
				}
			}
		#else // Windows
			char *homedir = getenv("USERPROFILE");
			if (homedir == NULL) homedir = "data"; // WIN 9x/Me
		#endif
		home_dir += homedir;
	}

	// Find user's config dir
	#ifndef _WIN32 // POSIX
	{
		char const* conf = getenv("XDG_CONFIG_HOME");
		if (conf) user_config_dir = (fs::path(conf) / "stuntrally").string();
		else user_config_dir = (fs::path(home_dir) / ".config" / "stuntrally").string();
	}
	#else // Windows
	{
		// Open AppData directory
		std::string str;
		ITEMIDLIST* pidl;
		char AppDir[MAX_PATH];
		HRESULT hRes = SHGetSpecialFolderLocation(NULL, CSIDL_APPDATA|CSIDL_FLAG_CREATE , &pidl);
		if (hRes == NOERROR)
		{
			SHGetPathFromIDList(pidl, AppDir);
			int i;
			for (i = 0; AppDir[i] != '\0'; i++) {
				if (AppDir[i] == '\\') str += '/';
				else str += AppDir[i];
			}
			user_config_dir = (fs::path(str) / "stuntrally").string();
		}
	}
	#endif
	// Create user's config dir
	CreateDir(user_config_dir, error_output);

	// Find user's data dir (for additional data)
	#ifdef _WIN32
	user_data_dir = user_config_dir;  // APPDATA/stuntrally
	#else
	{
		fs::path shareDir = SHARED_DATA_DIR;
		char const* xdg_data_home = getenv("XDG_DATA_HOME");
		user_data_dir = (xdg_data_home ? xdg_data_home / shortDir : fs::path(home_dir) / ".local" / shareDir).string();
	}
	#endif
	// Create user's data dir and its children
	CreateDir(user_data_dir, error_output);
	CreateDir(GetTrackRecordsPath(), error_output);
	CreateDir(GetScreenShotDir(), error_output);
	CreateDir(GetTrackPathUser(), error_output);  // user tracks
	CreateDir(GetTrackPathUser()+"/_previews", error_output);
	CreateDir(GetReplayPath(), error_output);
	CreateDir(GetGhostsPath(), error_output);

	// Find game data dir and defaults config dir
	char *datadir = getenv("STUNTRALLY_DATA_ROOT");
	if (datadir)
		game_data_dir = std::string(datadir);
	else
	{	fs::path shareDir = SHARED_DATA_DIR;
		Paths dirs;

		// Adding users data dir
		// TODO: Disabled for now until this is handled properly
		//dirs.push_back(user_data_dir);

		// Adding relative path from installed executable
		dirs.push_back(execname().parent_path().parent_path() / shareDir);
		// Adding relative path for running from sources
		dirs.push_back(execname().parent_path().parent_path() / "data");
		dirs.push_back(execname().parent_path().parent_path());
		dirs.push_back(execname().parent_path() / "data");
		dirs.push_back(execname().parent_path());
		#ifndef _WIN32
		// Adding XDG_DATA_DIRS
		{
			char const* xdg_data_dirs = getenv("XDG_DATA_DIRS");
			std::istringstream iss(xdg_data_dirs ? xdg_data_dirs : "/usr/local/share/:/usr/share/");
			for (std::string p; std::getline(iss, p, ':'); dirs.push_back(p / shortDir)) {}
		}
		#endif
		// TODO: Adding path from config file

		// Loop through the paths and pick the first one that contain some data
		for (Paths::const_iterator p = dirs.begin(); p != dirs.end(); ++p) {
			// Data dir
			if (fs::exists(*p / "hud")) game_data_dir = p->string();
			// Config dir
			if (fs::exists(*p / "config"))
				game_config_dir = (*p / "config").string();
			// Check if both are found
			if (!game_data_dir.empty() && !game_config_dir.empty()) break;
		}
	}

	// Find cache dir
	#ifdef _WIN32
	cache_dir = user_config_dir + "/cache";  // APPDATA/stuntrally/cache
	#else
	char const* xdg_cache_home = getenv("XDG_CACHE_HOME");
	cache_dir = (xdg_cache_home ? xdg_cache_home / shortDir : fs::path(home_dir) / ".cache" / shortDir).string();
	#endif
	// Create cache dir
	CreateDir(cache_dir, error_output);
	CreateDir(GetShaderCacheDir(), error_output);

	// Print diagnostic info
	std::stringstream out;
	out << "--- Directories: ---" << ogre_plugin_dir << std::endl;
	out << "Ogre plugin:  " << ogre_plugin_dir << std::endl;
	out << "Home:         " << home_dir << std::endl;
	out << "Default cfg:  " << GetGameConfigDir() << std::endl;
	out << "User cfg:     " << GetUserConfigDir() << std::endl;
	out << "Data:         " << GetDataPath() << std::endl;
	out << "User data:    " << GetUserDataDir() << std::endl;
	out << "Cache:        " << GetCacheDir() << std::endl;
	out << "Shader cache: " << GetShaderCacheDir() << std::endl;
	out << "Log:          " << GetLogDir() << std::endl;
	info_output << out.str();
}
BOOL CJlaunchApp::InitInstance()
{
	// Standardinitialisierung
	// Wenn Sie diese Funktionen nicht nutzen und die Größe Ihrer fertigen 
	//  ausführbaren Datei reduzieren wollen, sollten Sie die nachfolgenden
	//  spezifischen Initialisierungsroutinen, die Sie nicht benötigen, entfernen.
#ifdef _AFXDLL
	Enable3dControls();			// Diese Funktion bei Verwendung von MFC in gemeinsam genutzten DLLs aufrufen
#else
	Enable3dControlsStatic();	// Diese Funktion bei statischen MFC-Anbindungen aufrufen
#endif
	char cmd[MAX_PATH];
	int n = strlen(m_pszHelpFilePath);
	while (n-- > 0 && m_pszHelpFilePath[n] != '\\');
	strncpy(cmd, m_pszHelpFilePath, n+1);
	cmd[n+1] = 0;
	strcat(cmd, "zeta.bat");	
	// m_sCmd = "c:\\zeta-1.5\\bin\\zeta.bat";

	BROWSEINFO info;
	char path[MAX_PATH];
	info.hwndOwner = NULL; // GetSafeHwnd();
	/*
	SHGetSpecialFolderLocation(
		NULL, CSIDL_PROFILE, &info.pidlRoot
	);
	*/
	info.pidlRoot = NULL;
	info.pszDisplayName = (LPTSTR)path;
	info.lpszTitle = "Select Folder To Start ZETA Within";
	info.ulFlags = 0; // BIF_NEWDIALOGSTYLE|BIF_USENEWUI|BIF_SHAREABLE
	info.lpfn = NULL;
	info.lParam = 0;
	info.iImage = 0;
	CoInitialize(NULL);
	LPITEMIDLIST res = SHBrowseForFolder(&info);
	if (res == NULL){
		exit(1);
		/*
		MessageBox(
			NULL, (LPCTSTR)"Error",
			
				(LPCTSTR)"Cannot Launch ZETA",
				0
		);
		*/
	}
	SHGetPathFromIDList(
		res,
		path
	);
	STARTUPINFO sinfo;
	PROCESS_INFORMATION pinfo;
	GetStartupInfo(&sinfo);
	int cres = CreateProcess(
				// NULL, (LPSTR)(LPCSTR)m_sCmd,
				cmd, NULL, // (LPSTR)(LPCSTR)m_sCmd, NULL,
				NULL,
				NULL,
				FALSE,
				CREATE_NO_WINDOW,
				NULL,
				path,
				&sinfo,
				&pinfo
			);		
	if (cres == 0){
		char msg[1024];
		FormatMessage(
			FORMAT_MESSAGE_FROM_SYSTEM,
			NULL,
			GetLastError(),
			0,
			msg,
			1024,
			NULL
		);
		MessageBox(
			NULL, (LPCTSTR)msg, 
			(LPCTSTR)"Cannot Launch ZETA",
			MB_OK | MB_ICONSTOP
		);
		exit(2);
	}		

	return FALSE;

}
///////////////////////////////////////////////////////////////////////////////
// BrowseCallbackProc - SHBrowseForFolder callback function
static int CALLBACK BrowseCallbackProc(HWND hwnd,		// Window handle to the browse dialog box
									   UINT uMsg,		// Value identifying the event
									   LPARAM lParam,	// Value dependent upon the message 
									   LPARAM lpData)	// Application-defined value that was 
														// specified in the lParam member of the 
														// BROWSEINFO structure
{
	switch (uMsg)
	{
		case BFFM_INITIALIZED:		// sent when the browse dialog box has finished initializing. 
		{
			// remove context help button from dialog caption
			LONG lStyle = ::GetWindowLong(hwnd, GWL_STYLE);
			lStyle &= ~DS_CONTEXTHELP;
			::SetWindowLong(hwnd, GWL_STYLE, lStyle);
			lStyle = ::GetWindowLong(hwnd, GWL_EXSTYLE);
			lStyle &= ~WS_EX_CONTEXTHELP;
			::SetWindowLong(hwnd, GWL_EXSTYLE, lStyle);

			// set initial directory
			::SendMessage(hwnd, BFFM_SETSELECTION, TRUE, lpData);

			// find the folder tree and make dialog larger
			HWND hwndTree = FindWindowEx(hwnd, NULL, _T("SysTreeView32"), NULL);
			if (hwndTree)
			{
#if 0
				// make the dialog larger
				CRect rectDlg;
				::GetWindowRect(hwnd, &rectDlg);
				rectDlg.right += 40;
				rectDlg.bottom += 30;
				MoveWindowX(hwnd, rectDlg, TRUE);
				::GetClientRect(hwnd, &rectDlg);

				// move the Cancel button
				CRect rectCancel(0, 0, 0, 0);
				HWND hwndCancel = ::GetDlgItem(hwnd, IDCANCEL);
				if (hwndCancel)
					::GetWindowRect(hwndCancel, &rectCancel);
				ScreenToClientX(hwnd, &rectCancel);
				int h = rectCancel.Height();
				int w = rectCancel.Width();
				rectCancel.bottom = rectDlg.bottom - 5;
				rectCancel.top = rectCancel.bottom - h;
				rectCancel.right = rectDlg.right - 5;
				rectCancel.left = rectCancel.right - w;
				if (hwndCancel)
					MoveWindowX(hwndCancel, rectCancel, FALSE);

				// move the OK button
				CRect rectOK(0, 0, 0, 0);
				HWND hwndOK = ::GetDlgItem(hwnd, IDOK);
				if (hwndOK)
					::GetWindowRect(hwndOK, &rectOK);
				ScreenToClientX(hwnd, &rectOK);
				rectOK.bottom = rectDlg.bottom - 5;
				rectOK.top = rectOK.bottom - h;
				rectOK.right = rectCancel.left - 10;
				rectOK.left = rectOK.right - w;
				if (hwndOK)
					MoveWindowX(hwndOK, rectOK, FALSE);

				// expand the folder tree to fill the dialog
				CRect rectTree;
				::GetWindowRect(hwndTree, &rectTree);
				ScreenToClientX(hwnd, &rectTree);
				rectTree.top = 5;
				rectTree.left= 5;
				rectTree.bottom = rectOK.top - 5;
				rectTree.right = rectDlg.right - 5;
				MoveWindowX(hwndTree, rectTree, FALSE);
#endif
			}
			else
			{
//				TRACE(_T("ERROR - tree control not found.\n"));
				_ASSERTE(hwndTree);
			}
		}
		break;

		case BFFM_SELCHANGED:		// sent when the selection has changed
		{
			TCHAR szDir[MAX_PATH*2] = { 0 };

			// fail if non-filesystem
			BOOL bRet = SHGetPathFromIDList((LPITEMIDLIST) lParam, szDir);
			if (bRet)
			{
				// fail if folder not accessible
				if (_taccess(szDir, 00) != 0)
				{
					bRet = FALSE;
				}
				else
				{
					SHFILEINFO sfi;
					::SHGetFileInfo((LPCTSTR)lParam, 0, &sfi, sizeof(sfi), 
							SHGFI_PIDL | SHGFI_ATTRIBUTES);
//					TRACE(_T("dwAttributes=0x%08X\n"), sfi.dwAttributes);

					// fail if pidl is a link
					if (sfi.dwAttributes & SFGAO_LINK)
					{
//						TRACE(_T("SFGAO_LINK\n"));
						bRet = FALSE;
					}
				}
			}

			// if invalid selection, disable the OK button
			if (!bRet)
			{
				::EnableWindow(GetDlgItem(hwnd, IDOK), FALSE);
			}

//			TRACE(_T("szDir=%s\n"), szDir);
		}
		break;
	}
         
	return 0;
}
STDMETHODIMP CDDShellExt::Initialize(LPCITEMIDLIST pidlFolder,LPDATAOBJECT pDO,HKEY hProgID)
{
	(void)hProgID;
	if(!connected)
	{
		bool b = m_ac.connectToServer();

		if (b==true)
		{
			connected=true;
		}
		else
			return E_FAIL;
	}

	FORMATETC fmt={CF_HDROP,NULL,DVASPECT_CONTENT,-1,TYMED_HGLOBAL};
	STGMEDIUM stg={TYMED_HGLOBAL};
	HDROP hDrop;

	fDestDir[0]=0;
	if (!SHGetPathFromIDList(pidlFolder,fDestDir))
	{
		#ifdef CATCHCOPY_EXPLORER_PLUGIN_DEBUG
		MessageBox(NULL,L"Initialize",L"E_FAIL 1",MB_OK);
		#endif // CATCHCOPY_EXPLORER_PLUGIN_DEBUG
		return E_FAIL;
	}

	// Detect if it's explorer that started the operation by enumerating available
	// clipboard formats and searching for one that only explorer uses
	IEnumFORMATETC *en;
	FORMATETC fmt2;
	WCHAR fmtName[256]=L"\0";
	fFromExplorer=false;
	pDO->EnumFormatEtc(DATADIR_GET,&en);
	while(en->Next(1,&fmt2,NULL)==S_OK){
		GetClipboardFormatName(fmt2.cfFormat,fmtName,256);
		if (!wcscmp(fmtName,CFSTR_SHELLIDLIST)) fFromExplorer=true;
	}
	en->Release();

	// Look for CF_HDROP data in the data object. If there
	// is no such data, return an error back to Explorer.
	if (FAILED(pDO->GetData(&fmt,&stg)))
	{
		#ifdef CATCHCOPY_EXPLORER_PLUGIN_DEBUG
		MessageBox(NULL,L"Initialize",L"E_INVALIDARG 2",MB_OK);
		#endif // CATCHCOPY_EXPLORER_PLUGIN_DEBUG
		return E_INVALIDARG;
	}

	// Get a pointer to the actual data.
	hDrop=(HDROP)GlobalLock(stg.hGlobal);

	// Make sure it worked.
	if (hDrop==NULL)
	{
		#ifdef CATCHCOPY_EXPLORER_PLUGIN_DEBUG
		MessageBox(NULL,L"Initialize",L"E_INVALIDARG 1",MB_OK);
		#endif // CATCHCOPY_EXPLORER_PLUGIN_DEBUG
		return E_INVALIDARG;
	}

	UINT numFiles,i;
	WCHAR fn[MAX_PATH]=L"";

	numFiles=DragQueryFile(hDrop,0xFFFFFFFF,NULL,0);

	if (numFiles)
	{
		for(i=0;i<numFiles;++i)
		{
			if(DragQueryFile(hDrop,i,fn,MAX_PATH))
				sources.push_back(fn);
		}
	}

	GlobalUnlock(stg.hGlobal);
	ReleaseStgMedium(&stg);

	return S_OK;
}
Exemple #10
0
CBrowseFolder::retVal CBrowseFolder::Show(HWND parent, CString& path, const CString& sDefaultPath /* = CString() */)
{
    retVal ret = OK;		//assume OK
    m_sDefaultPath = sDefaultPath;
    if (m_sDefaultPath.IsEmpty() && !path.IsEmpty()) {
        while (!PathFileExists(path) && !path.IsEmpty()) {
            CString p = path.Left(path.ReverseFind(L'\\'));
            if ((p.GetLength() == 2) && (p[1] == L':')) {
                p += L"\\";
                if (p.Compare(path) == 0)
                    p.Empty();
            }
            if (p.GetLength() < 2)
                p.Empty();
            path = p;
        }
        // if the result path already contains a path, use that as the default path
        m_sDefaultPath = path;
    }

    HRESULT hr;

    // Create a new common open file dialog
    IFileOpenDialog* pfd = NULL;
    hr = CoCreateInstance(CLSID_FileOpenDialog, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pfd));
    if (SUCCEEDED(hr)) {
        // Set the dialog as a folder picker
        DWORD dwOptions;
        if (SUCCEEDED(hr = pfd->GetOptions(&dwOptions))) {
            hr = pfd->SetOptions(dwOptions | FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM | FOS_PATHMUSTEXIST);
        }

        // Set a title
        if (SUCCEEDED(hr)) {
            TCHAR * nl = _tcschr(m_title, '\n');
            if (nl)
                *nl = 0;
            pfd->SetTitle(m_title);
        }

        // set the default folder
        if (SUCCEEDED(hr)) {
            typedef HRESULT(WINAPI *SHCIFPN)(PCWSTR pszPath, IBindCtx * pbc, REFIID riid, void ** ppv);

            SHCIFPN pSHCIFPN = hLib.GetProcAddress<SHCIFPN>("SHCreateItemFromParsingName");
            if (pSHCIFPN) {
                IShellItem *psiDefault = 0;
                hr = pSHCIFPN(m_sDefaultPath, NULL, IID_PPV_ARGS(&psiDefault));
                if (SUCCEEDED(hr)) {
                    hr = pfd->SetFolder(psiDefault);
                    psiDefault->Release();
                }
            }

        }

        // Show the open file dialog
        if (SUCCEEDED(hr) && SUCCEEDED(hr = pfd->Show(parent))) {
            // Get the selection from the user
            IShellItem* psiResult = NULL;
            hr = pfd->GetResult(&psiResult);
            if (SUCCEEDED(hr)) {
                PWSTR pszPath = NULL;
                hr = psiResult->GetDisplayName(SIGDN_FILESYSPATH, &pszPath);
                if (SUCCEEDED(hr)) {
                    path = pszPath;
                    CoTaskMemFree(pszPath);
                }
                psiResult->Release();
            } else
                ret = CANCEL;
        } else
            ret = CANCEL;

        pfd->Release();
    } else {
        BROWSEINFO browseInfo = {};
        browseInfo.hwndOwner = parent;
        browseInfo.pidlRoot = m_root;
        browseInfo.pszDisplayName = m_displayName;
        browseInfo.lpszTitle = m_title;
        browseInfo.ulFlags = m_style;
        browseInfo.lParam = reinterpret_cast<LPARAM>(this);

        PCIDLIST_ABSOLUTE itemIDList = SHBrowseForFolder(&browseInfo);

        //is the dialog canceled?
        if (!itemIDList)
            ret = CANCEL;

        if (ret != CANCEL) {
            if (!SHGetPathFromIDList(itemIDList, path.GetBuffer(MAX_PATH)))		// MAX_PATH ok. Explorer can't handle paths longer than MAX_PATH.
                ret = NOPATH;

            path.ReleaseBuffer();

            CoTaskMemFree((LPVOID)itemIDList);
        }
    }

    return ret;
}
///////////////////////////////////////////////////////////////////////////////
//
// XBrowseForFolder()
//
// Purpose:     Invoke the SHBrowseForFolder API.  If lpszInitialFolder is
//              supplied, it will be the folder initially selected in the tree 
//              folder list.  Otherwise, the initial folder will be set to the 
//              current directory.  The selected folder will be returned in 
//              lpszBuf.
//
// Parameters:  hWnd              - handle to the owner window for the dialog
//              lpszInitialFolder - initial folder in tree;  if NULL, the initial
//                                  folder will be the current directory.
//              lpszBuf           - buffer for the returned folder path
//              dwBufSize         - size of lpszBuf in TCHARs
//
// Returns:     BOOL - TRUE = success;  FALSE = user hit Cancel
//
BOOL XBrowseForFolder(HWND hWnd,
					  LPCTSTR lpszInitialFolder,
					  LPTSTR lpszBuf,
					  DWORD dwBufSize)
{
	_ASSERTE(lpszBuf);
	_ASSERTE(dwBufSize >= MAX_PATH);

	if (lpszBuf == NULL || dwBufSize < MAX_PATH)
		return FALSE;

	lpszBuf[0] = _T('\0');

	TCHAR szInitialPath[MAX_PATH*2];
	ZeroMemory(szInitialPath, sizeof(szInitialPath));

	if (lpszInitialFolder && lpszInitialFolder[0] != _T('\0'))
	{
		_tcsncpy(szInitialPath, lpszInitialFolder, 
					sizeof(szInitialPath)/sizeof(TCHAR)-2);
	}
	else
	{
		// no initial folder, set to current directory
		::GetCurrentDirectory(sizeof(szInitialPath)/sizeof(TCHAR)-2, 
				szInitialPath);
	}

	BROWSEINFO bi;
	ZeroMemory(&bi, sizeof(BROWSEINFO));

	bi.hwndOwner = hWnd;
	bi.ulFlags   = BIF_RETURNONLYFSDIRS;	// do NOT use BIF_NEWDIALOGSTYLE, 
											// BIF_EDITBOX, or BIF_STATUSTEXT
	bi.lpfn      = BrowseCallbackProc;
	bi.lParam    = (LPARAM) szInitialPath;

	LPITEMIDLIST pidl = SHBrowseForFolder(&bi);

	BOOL bRet = FALSE;

	if (pidl)
	{
		TCHAR szBuffer[MAX_PATH*2];
		szBuffer[0] = _T('\0');

		if (SHGetPathFromIDList(pidl, szBuffer))
		{
			ZeroMemory(lpszBuf, dwBufSize);
			_tcsncpy(lpszBuf, szBuffer, dwBufSize-1);
			bRet = TRUE;
		}
		else
		{
//			TRACE(_T("SHGetPathFromIDList failed\n"));
		}

		IMalloc *pMalloc = NULL; 
		if (SUCCEEDED(SHGetMalloc(&pMalloc)) && pMalloc) 
		{  
			pMalloc->Free(pidl);  
			pMalloc->Release(); 
		}
	}

	return bRet;
}
/* #FN#
   Fills a branch of the TreeView control.
   
   Given the shell folder, enumerate the subitems of this folder, and
   add the appropriate items to the tree. This function enumerates the
   items in the folder identifed by lpsf. Note that since we are filling
   the left hand pane, we will only add items that are folders and/or
   have sub-folders. We *could* put all items in here if we wanted, but
   that's not the intent. */
void
/* #AS#
   Nothing */
CShellTree::
FillTreeView(
	LPSHELLFOLDER lpsf,   /* #IN# Pointer to shell folder that we want to enumerate items */
	LPITEMIDLIST  lpifq,  /* #IN# Fully qualified item id list to the item that we are enumerating items for; in other words, this is the PIDL to the item identified by the lpsf parameter */
	HTREEITEM     hParent /* #IN# Parent node */
)
{
	TV_ITEM         tvi;	/* TreeView Item */
	TV_INSERTSTRUCT tvins;	/* TreeView Insert Struct */

	HTREEITEM     hPrev         = NULL;	/* Previous Item Added */
	LPSHELLFOLDER lpsf2         = NULL;
	LPENUMIDLIST  lpe           = NULL;
	LPITEMIDLIST  lpi           = NULL;
	LPITEMIDLIST  lpifqThisItem = NULL;
	LPTVITEMDATA  lptvid        = NULL;
	LPMALLOC      lpMalloc      = NULL;

	ULONG   ulFetched = 0;
	HWND    hwnd      = ::GetParent( m_hWnd );
	char    szBuff[ MAX_PATH + 1 ];
	char    szPath[ MAX_PATH + 1 ];
	HRESULT hr;

	/* Allocate a shell memory object */
	hr = ::SHGetMalloc( &lpMalloc );
	if( FAILED(hr) )
		return;

	if( SUCCEEDED(hr) )
	{
		/* Get the IEnumIDList object for the given folder */
		hr = lpsf->EnumObjects( hwnd, SHCONTF_FOLDERS | SHCONTF_NONFOLDERS | SHCONTF_INCLUDEHIDDEN, &lpe );

		if( S_OK == hr && lpe )
		{
			/* Enumerate throught the list of folder and non-folder objects */
			while( S_OK == lpe->Next( 1, &lpi, &ulFetched ) )
			{
				/* Create a fully qualified path to the current item. The SH* shell API's
				   take a fully qualified path pidl, (see GetIcon above where I call
				   SHGetFileInfo) whereas the interface methods take a relative path pidl */
				ULONG ulAttrs = SFGAO_FOLDER | SFGAO_HASSUBFOLDER;

				if( !m_bFolderMode )
					ulAttrs |= SFGAO_FILESYSTEM | SFGAO_LINK;

				/* Determine what type of object we have */
				lpsf->GetAttributesOf( 1, (const struct _ITEMIDLIST **)&lpi, &ulAttrs );

				if( m_bFolderMode && ulAttrs & (SFGAO_HASSUBFOLDER | SFGAO_FOLDER) ||
				  (!m_bFolderMode && ulAttrs & (SFGAO_HASSUBFOLDER | SFGAO_FOLDER | SFGAO_FILESYSTEM) && !(ulAttrs & SFGAO_LINK)) )
				{
					tvi.mask = TVIF_TEXT | TVIF_IMAGE | TVIF_SELECTEDIMAGE | TVIF_PARAM;
					/* We need this next if statement so that we don't add things like
					   the MSN to our tree. MSN is not a folder, but according to the
					   shell it has subfolders */
					/* OK, let's get some memory for our ITEMDATA struct */
					lptvid = (LPTVITEMDATA)lpMalloc->Alloc( sizeof(TVITEMDATA) );
					if( !lptvid )
						goto Done; /* Error - could not allocate memory */

					/* Now get the friendly name that we'll put in the treeview */
					if( !GetName( lpsf, lpi, SHGDN_NORMAL, szBuff ) )
						goto Done; /* Error - could not get friendly name */

					tvi.pszText    = szBuff;
					tvi.cchTextMax = MAX_PATH;

					/* Allocate/create the fully qualified PIDL, consisting
					   of the parents full PIDL and our relative PIDL */
					lpifqThisItem = ConcatPidls( lpifq, lpi );

					if( ulAttrs & SFGAO_FOLDER && (ulAttrs & SFGAO_HASSUBFOLDER ||
						/* There are not any subfolders but what about files? */
						(!m_bFolderMode && SHGetPathFromIDList( lpifqThisItem, szPath ) && !IsFolderEmpty( szPath ))) )
					{
						/* This item has sub-folders, so let's put the + in the TreeView.
						   The first time the user clicks on the item, we'll populate the
						   sub-folders */
						tvi.cChildren = 1;
						tvi.mask |= TVIF_CHILDREN;
					}
					/* Now, make a copy of the ITEMIDLIST (non-qualified) */
					lptvid->lpi = CopyITEMID( lpMalloc, lpi );

					tvi.iImage =
						GetItemIcon( lpifqThisItem,
									 SHGFI_PIDL |
									 SHGFI_SYSICONINDEX |
									 SHGFI_SMALLICON );

					tvi.iSelectedImage =
						GetItemIcon( lpifqThisItem,
									 SHGFI_PIDL |
									 SHGFI_SYSICONINDEX |
									 SHGFI_SMALLICON |
									 SHGFI_OPENICON );

					lptvid->lpsfParent = lpsf; /* Store the parent folders SF */
					lpsf->AddRef();            /* Increment our saved reference */

					/* Now create another PIDL from our Full parents PIDL and
					   the releative one that we'll save */
					lptvid->lpifq = ConcatPidls( lpifq, lpi );

					/* Populate the TreeView Insert Struct. The item is the one
					   filled above. Insert it after the last item inserted at
					   this level. And indicate this is a root entry */
					tvi.lParam         = (LPARAM)lptvid;
					tvins.item         = tvi;
					tvins.hInsertAfter = hPrev;
					tvins.hParent      = hParent;

					/* Add the item to the tree */
					hPrev = InsertItem( &tvins );

					/* Free this item with task allocator */
					lpMalloc->Free( lpifqThisItem );
					lpifqThisItem = 0;
				}
				lpMalloc->Free( lpi );  /* Free the pidl that the shell gave us */
				lpi = 0;
			}
		}
	}
	else
		return;

Done:
	if( lpe )
		lpe->Release();

	/* The following 2 if statements will only be TRUE if we got here
	   on an error condition from the "goto" statement. Otherwise, we
	   free this memory at the end of the while loop above */
	if( lpi && lpMalloc )
		lpMalloc->Free( lpi );
	if( lpifqThisItem && lpMalloc )
		lpMalloc->Free( lpifqThisItem );

	if( lpMalloc )
		lpMalloc->Release();

} /* #OF# CShellTree::FillTreeView */
Exemple #13
0
INT_PTR CRecreateDlg::RecreateDlgProc(HWND hDlg, UINT messg, WPARAM wParam, LPARAM lParam)
{
#define UM_USER_CONTROLS (WM_USER+121)
#define UM_FILL_CMDLIST (WM_USER+122)

	CRecreateDlg* pDlg = NULL;
	if (messg == WM_INITDIALOG)
	{
		pDlg = (CRecreateDlg*)lParam;
		pDlg->mh_Dlg = hDlg;
		SetWindowLongPtr(hDlg, DWLP_USER, lParam);
	}
	else
	{
		pDlg = (CRecreateDlg*)GetWindowLongPtr(hDlg, DWLP_USER);
	}
	if (!pDlg)
	{
		return FALSE;
	}

	switch (messg)
	{
		case WM_INITDIALOG:
		{
			LRESULT lbRc = FALSE;
			

			SendMessage(hDlg, WM_SETICON, ICON_BIG, (LPARAM)hClassIcon);
			SendMessage(hDlg, WM_SETICON, ICON_SMALL, (LPARAM)hClassIconSm);

			HMENU hSysMenu = GetSystemMenu(hDlg, FALSE);
			InsertMenu(hSysMenu, 0, MF_BYPOSITION, MF_SEPARATOR, 0);
			InsertMenu(hSysMenu, 0, MF_BYPOSITION | MF_STRING | MF_ENABLED
					   | ((GetWindowLong(ghOpWnd,GWL_EXSTYLE)&WS_EX_TOPMOST) ? MF_CHECKED : 0),
					   ID_RESETCMDHISTORY, _T("Reset command history..."));


			SendDlgItemMessage(hDlg, tRunAsPassword, WM_SETFONT, (LPARAM)(HFONT)GetStockObject(DEFAULT_GUI_FONT), 0);

			//#ifdef _DEBUG
			//SetWindowPos(ghOpWnd, HWND_NOTOPMOST, 0,0,0,0, SWP_NOSIZE|SWP_NOMOVE);
			//#endif

			SendMessage(hDlg, UM_FILL_CMDLIST, TRUE, 0);
			
			RConStartArgs* pArgs = pDlg->mp_Args;
			_ASSERTE(pArgs);
			LPCWSTR pszCmd = pArgs->pszSpecialCmd
			                 ? pArgs->pszSpecialCmd
			                 : gpConEmu->ActiveCon()->RCon()->GetCmd();
			//int nId = SendDlgItemMessage(hDlg, IDC_RESTART_CMD, CB_FINDSTRINGEXACT, -1, (LPARAM)pszCmd);
			//if (nId < 0) SendDlgItemMessage(hDlg, IDC_RESTART_CMD, CB_INSERTSTRING, 0, (LPARAM)pszCmd);
			LPCWSTR pszSystem = gpSet->GetCmd();
			//if (pszSystem != pszCmd && (pszSystem && pszCmd && (lstrcmpi(pszSystem, pszCmd) != 0)))
			//{
			//	nId = SendDlgItemMessage(hDlg, IDC_RESTART_CMD, CB_FINDSTRINGEXACT, -1, (LPARAM)pszSystem);
			//	if (nId < 0) SendDlgItemMessage(hDlg, IDC_RESTART_CMD, CB_INSERTSTRING, pArgs->pszSpecialCmd ? -1 : 0, (LPARAM)pszSystem);
			//}
			//LPCWSTR pszHistory = gpSet->HistoryGet();
			//if (pszHistory)
			//{
			//	while (*pszHistory)
			//	{
			//		nId = SendDlgItemMessage(hDlg, IDC_RESTART_CMD, CB_FINDSTRINGEXACT, -1, (LPARAM)pszHistory);
			//		if (nId < 0)
			//			SendDlgItemMessage(hDlg, IDC_RESTART_CMD, CB_INSERTSTRING, -1, (LPARAM)pszHistory);
			//		pszHistory += _tcslen(pszHistory)+1;
			//	}
			//}
			////// Обновить группы команд
			////gpSet->LoadCmdTasks(NULL);
			//int nGroup = 0;
			//const Settings::CommandTasks* pGrp = NULL;
			//while ((pGrp = gpSet->CmdTaskGet(nGroup++)))
			//{
			//	nId = SendDlgItemMessage(hDlg, IDC_RESTART_CMD, CB_FINDSTRINGEXACT, -1, (LPARAM)pGrp->pszName);
			//	if (nId < 0)
			//		SendDlgItemMessage(hDlg, IDC_RESTART_CMD, CB_INSERTSTRING, -1, (LPARAM)pGrp->pszName);
			//}

			if (pArgs->aRecreate == cra_RecreateTab)
			{
				SetDlgItemText(hDlg, IDC_RESTART_CMD, pszCmd);
				SetDlgItemText(hDlg, IDC_STARTUP_DIR, gpConEmu->ActiveCon()->RCon()->GetDir());
			}
			else
			{
				SetDlgItemText(hDlg, IDC_RESTART_CMD, pArgs->pszSpecialCmd ? pArgs->pszSpecialCmd : pszSystem);
				SetDlgItemText(hDlg, IDC_STARTUP_DIR, pArgs->pszStartupDir ? pArgs->pszStartupDir : L"");
			}
			//EnableWindow(GetDlgItem(hDlg, IDC_STARTUP_DIR), FALSE);
			//#ifndef _DEBUG
			//EnableWindow(GetDlgItem(hDlg, IDC_CHOOSE_DIR), FALSE);
			//#endif
			const wchar_t *pszUser, *pszDomain; BOOL bResticted;
			int nChecked = rbCurrentUser;
			wchar_t szCurUser[MAX_PATH*2+1]; DWORD nUserNameLen = countof(szCurUser);

			if (!GetUserName(szCurUser, &nUserNameLen)) szCurUser[0] = 0;

			wchar_t szRbCaption[MAX_PATH*3];
			lstrcpy(szRbCaption, L"Run as current &user: "******"UPN format" остается в pszUser
							lstrcpyn(szCurUser, pszUser, MAX_PATH);
							wcscat_c(szCurUser, L"@");
							lstrcpyn(szCurUser+_tcslen(szCurUser), pszDomain, MAX_PATH);
						}
						else
						{
							// "Старая" нотация domain\user
							lstrcpyn(szCurUser, pszDomain, MAX_PATH);
							wcscat_c(szCurUser, L"\\");
							lstrcpyn(szCurUser+_tcslen(szCurUser), pszUser, MAX_PATH);
						}
					}
					else
					{
						lstrcpyn(szCurUser, pszUser, countof(szCurUser));
					}
					SetDlgItemText(hDlg, tRunAsPassword, L"");
				}
			}

			SetDlgItemText(hDlg, tRunAsUser, szCurUser);
			CheckRadioButton(hDlg, rbCurrentUser, rbAnotherUser, nChecked);
			RecreateDlgProc(hDlg, UM_USER_CONTROLS, 0, 0);

			if (gOSVer.dwMajorVersion < 6)
			{
				// В XP и ниже это просто RunAs - с возможностью ввода имени пользователя и пароля
				//apiShowWindow(GetDlgItem(hDlg, cbRunAsAdmin), SW_HIDE);
				SetDlgItemTextA(hDlg, cbRunAsAdmin, "&Run as..."); //GCC hack. иначе не собирается
				// И уменьшить длину
				RECT rcBox; GetWindowRect(GetDlgItem(hDlg, cbRunAsAdmin), &rcBox);
				SetWindowPos(GetDlgItem(hDlg, cbRunAsAdmin), NULL, 0, 0, (rcBox.right-rcBox.left)/2, rcBox.bottom-rcBox.top,
				             SWP_NOMOVE|SWP_NOZORDER);
			}
			else if (gpConEmu->mb_IsUacAdmin || (pArgs && pArgs->bRunAsAdministrator))
			{
				CheckDlgButton(hDlg, cbRunAsAdmin, BST_CHECKED);

				if (gpConEmu->mb_IsUacAdmin)  // Только в Vista+ если GUI уже запущен под админом
				{
					EnableWindow(GetDlgItem(hDlg, cbRunAsAdmin), FALSE);
				}
				else if (gOSVer.dwMajorVersion < 6)
				{
					RecreateDlgProc(hDlg, WM_COMMAND, cbRunAsAdmin, 0);
				}
			}

			//}
			SetClassLongPtr(hDlg, GCLP_HICON, (LONG_PTR)hClassIcon);

			RECT rcBtnBox = {0};
			if (pArgs->aRecreate == cra_RecreateTab)
			{
				//GCC hack. иначе не собирается
				SetDlgItemTextA(hDlg, IDC_RESTART_MSG, "About to recreate console");
				SendDlgItemMessage(hDlg, IDC_RESTART_ICON, STM_SETICON, (WPARAM)LoadIcon(NULL,IDI_EXCLAMATION), 0);
				// Выровнять флажок по кнопке
				GetWindowRect(GetDlgItem(hDlg, IDC_START), &rcBtnBox);
				// Спрятать флажок "New window"
				ShowWindow(GetDlgItem(hDlg, cbRunInNewWindow), SW_HIDE);
				lbRc = TRUE;
			}
			else
			{
				//GCC hack. иначе не собирается
				SetDlgItemTextA(hDlg, IDC_RESTART_MSG,  "Create new console");

				CheckDlgButton(hDlg, cbRunInNewWindow, (pArgs->aRecreate == cra_CreateWindow) ? BST_CHECKED : BST_UNCHECKED);
				//if (pArgs->aRecreate == cra_CreateWindow)
				//{
				//	SetWindowText(hDlg, L"ConEmu - Create new window");
				//	//GCC hack. иначе не собирается
				//	SetDlgItemTextA(hDlg, IDC_RESTART_MSG,  "Create new window");
				//}
				//else
				//{
				//	//GCC hack. иначе не собирается
				//	SetDlgItemTextA(hDlg, IDC_RESTART_MSG,  "Create new console");
				//}

				SendDlgItemMessage(hDlg, IDC_RESTART_ICON, STM_SETICON, (WPARAM)LoadIcon(NULL,IDI_QUESTION), 0);
				POINT pt = {0,0};
				MapWindowPoints(GetDlgItem(hDlg, IDC_TERMINATE), hDlg, &pt, 1);
				DestroyWindow(GetDlgItem(hDlg, IDC_TERMINATE));
				SetWindowPos(GetDlgItem(hDlg, IDC_START), NULL, pt.x, pt.y, 0,0, SWP_NOSIZE|SWP_NOZORDER);
				SetDlgItemText(hDlg, IDC_START, L"&Start");
				DestroyWindow(GetDlgItem(hDlg, IDC_WARNING));
				// Выровнять флажок по кнопке
				GetWindowRect(GetDlgItem(hDlg, IDC_START), &rcBtnBox);
				SetFocus(GetDlgItem(hDlg, IDC_RESTART_CMD));
			}

			if (rcBtnBox.left)
			{
				// Выровнять флажок по кнопке
				MapWindowPoints(NULL, hDlg, (LPPOINT)&rcBtnBox, 2);
				RECT rcBox; GetWindowRect(GetDlgItem(hDlg, cbRunAsAdmin), &rcBox);
				POINT pt;
				pt.x = rcBtnBox.left - (rcBox.right - rcBox.left) - 5;
				pt.y = rcBtnBox.top + ((rcBtnBox.bottom-rcBtnBox.top) - (rcBox.bottom-rcBox.top))/2;
				SetWindowPos(GetDlgItem(hDlg, cbRunAsAdmin), NULL, pt.x, pt.y, 0,0, SWP_NOSIZE|SWP_NOZORDER);
				SetFocus(GetDlgItem(hDlg, IDC_RESTART_CMD));
			}

			if (pArgs->aRecreate != cra_RecreateTab)
			{
				POINT pt = {};
				MapWindowPoints(GetDlgItem(hDlg, cbRunAsAdmin), hDlg, &pt, 1);
				RECT rcBox2; GetWindowRect(GetDlgItem(hDlg, cbRunInNewWindow), &rcBox2);
				SetWindowPos(GetDlgItem(hDlg, cbRunInNewWindow), NULL,
					pt.x-(rcBox2.right-rcBox2.left), pt.y, 0,0, SWP_NOSIZE);
			}

			RECT rect;
			GetWindowRect(hDlg, &rect);
			RECT rcParent;
			GetWindowRect(ghWnd, &rcParent);
			MoveWindow(hDlg,
			           (rcParent.left+rcParent.right-rect.right+rect.left)/2,
			           (rcParent.top+rcParent.bottom-rect.bottom+rect.top)/2,
			           rect.right - rect.left, rect.bottom - rect.top, false);

			PostMessage(hDlg, (WM_APP+1), 0,0);
			return lbRc;
		}
		case (WM_APP+1):
			gpConEmu->SetSkipOnFocus(FALSE);
			return FALSE;
		case WM_CTLCOLORSTATIC:

			if (GetDlgItem(hDlg, IDC_WARNING) == (HWND)lParam)
			{
				SetTextColor((HDC)wParam, 255);
				HBRUSH hBrush = GetSysColorBrush(COLOR_3DFACE);
				SetBkMode((HDC)wParam, TRANSPARENT);
				return (INT_PTR)hBrush;
			}

			break;
		//case WM_GETICON:

		//	if (wParam==ICON_BIG)
		//	{
		//		/*SetWindowLong(hWnd2, DWL_MSGRESULT, (LRESULT)hClassIcon);
		//		return 1;*/
		//	}
		//	else
		//	{
		//		SetWindowLongPtr(hDlg, DWLP_MSGRESULT, (LRESULT)hClassIconSm);
		//		return 1;
		//	}

		//	return 0;

		case UM_FILL_CMDLIST:
		{
			RConStartArgs* pArgs = pDlg->mp_Args;
			_ASSERTE(pArgs);

			LPCWSTR pszCmd = pArgs->pszSpecialCmd
			                 ? pArgs->pszSpecialCmd
			                 : gpConEmu->ActiveCon()->RCon()->GetCmd();
			int nId = SendDlgItemMessage(hDlg, IDC_RESTART_CMD, CB_FINDSTRINGEXACT, -1, (LPARAM)pszCmd);

			if (nId < 0) SendDlgItemMessage(hDlg, IDC_RESTART_CMD, CB_INSERTSTRING, 0, (LPARAM)pszCmd);

			LPCWSTR pszSystem = gpSet->GetCmd();

			if (pszSystem != pszCmd && (pszSystem && pszCmd && (lstrcmpi(pszSystem, pszCmd) != 0)))
			{
				nId = SendDlgItemMessage(hDlg, IDC_RESTART_CMD, CB_FINDSTRINGEXACT, -1, (LPARAM)pszSystem);

				if (nId < 0) SendDlgItemMessage(hDlg, IDC_RESTART_CMD, CB_INSERTSTRING, pArgs->pszSpecialCmd ? -1 : 0, (LPARAM)pszSystem);
			}

			if (wParam)
			{
				LPCWSTR pszHistory = gpSet->HistoryGet();

				if (pszHistory)
				{
					while (*pszHistory)
					{
						nId = SendDlgItemMessage(hDlg, IDC_RESTART_CMD, CB_FINDSTRINGEXACT, -1, (LPARAM)pszHistory);
						if (nId < 0)
							SendDlgItemMessage(hDlg, IDC_RESTART_CMD, CB_INSERTSTRING, -1, (LPARAM)pszHistory);

						pszHistory += _tcslen(pszHistory)+1;
					}
				}
			}

			//// Обновить группы команд
			//gpSet->LoadCmdTasks(NULL);

			int nGroup = 0;
			const Settings::CommandTasks* pGrp = NULL;
			while ((pGrp = gpSet->CmdTaskGet(nGroup++)))
			{
				nId = SendDlgItemMessage(hDlg, IDC_RESTART_CMD, CB_FINDSTRINGEXACT, -1, (LPARAM)pGrp->pszName);
				if (nId < 0)
					SendDlgItemMessage(hDlg, IDC_RESTART_CMD, CB_INSERTSTRING, -1, (LPARAM)pGrp->pszName);
			}
		}
		return 0;

		case UM_USER_CONTROLS:
		{
			if (SendDlgItemMessage(hDlg, rbCurrentUser, BM_GETCHECK, 0, 0))
			{
				EnableWindow(GetDlgItem(hDlg, cbRunAsRestricted), TRUE);
				//BOOL lbText = SendDlgItemMessage(hDlg, cbRunAsRestricted, BM_GETCHECK, 0, 0) == 0;
				EnableWindow(GetDlgItem(hDlg, tRunAsUser), FALSE);
				EnableWindow(GetDlgItem(hDlg, tRunAsPassword), FALSE);
			}
			else
			{
				if (SendDlgItemMessage(hDlg, tRunAsUser, CB_GETCOUNT, 0, 0) == 0)
				{
					DWORD dwLevel = 3, dwEntriesRead = 0, dwTotalEntries = 0, dwResumeHandle = 0;
					NET_API_STATUS nStatus;
					USER_INFO_3 *info = NULL;
					nStatus = ::NetUserEnum(NULL, dwLevel, FILTER_NORMAL_ACCOUNT, (PBYTE*) & info,
					                        MAX_PREFERRED_LENGTH, &dwEntriesRead, &dwTotalEntries, &dwResumeHandle);

					if (nStatus == NERR_Success)
					{
						for(DWORD i = 0; i < dwEntriesRead; ++i)
						{
							// usri3_logon_server	"\\*"	wchar_t *
							if ((info[i].usri3_flags & UF_ACCOUNTDISABLE) == 0)
								SendDlgItemMessage(hDlg, tRunAsUser, CB_ADDSTRING, 0, (LPARAM)info[i].usri3_name);
						}

						::NetApiBufferFree(info);
					}
					else
					{
						// Добавить хотя бы текущего
						wchar_t szCurUser[MAX_PATH];

						if (GetWindowText(GetDlgItem(hDlg, tRunAsUser), szCurUser, countof(szCurUser)))
							SendDlgItemMessage(hDlg, tRunAsUser, CB_ADDSTRING, 0, (LPARAM)szCurUser);
					}
				}

				EnableWindow(GetDlgItem(hDlg, cbRunAsRestricted), FALSE);
				EnableWindow(GetDlgItem(hDlg, tRunAsUser), TRUE);
				EnableWindow(GetDlgItem(hDlg, tRunAsPassword), TRUE);
			}

			if (wParam == rbAnotherUser)
				SetFocus(GetDlgItem(hDlg, tRunAsUser));
		}
		return 0;

		case WM_SYSCOMMAND:
			if (LOWORD(wParam) == ID_RESETCMDHISTORY)
			{
				if (IDYES == MessageBox(hDlg, L"Clear command history?", gpConEmu->GetDefaultTitle(), MB_ICONEXCLAMATION|MB_YESNO|MB_DEFBUTTON2))
				{
                	gpSet->HistoryReset();
                	wchar_t* pszCmd = GetDlgItemText(hDlg, IDC_RESTART_CMD);
                	SendDlgItemMessage(hDlg, IDC_RESTART_CMD, CB_RESETCONTENT, 0,0);
                	SendMessage(hDlg, UM_FILL_CMDLIST, FALSE, 0);
                	if (pszCmd)
                	{
                		SetDlgItemText(hDlg, IDC_RESTART_CMD, pszCmd);
                		free(pszCmd);
                	}
				}
				SetWindowLongPtr(hDlg, DWLP_MSGRESULT, 0);
				return 1;
			}
			break;

		case WM_COMMAND:

			if (HIWORD(wParam) == BN_CLICKED)
			{
				switch(LOWORD(wParam))
				{
					case IDC_CHOOSE:
					{
						wchar_t *pszFilePath = NULL;
						int nLen = MAX_PATH*2;
						pszFilePath = (wchar_t*)calloc(nLen+3,2); // +2*'"'+\0

						if (!pszFilePath) return 1;

						OPENFILENAME ofn; memset(&ofn,0,sizeof(ofn));
						ofn.lStructSize=sizeof(ofn);
						ofn.hwndOwner = hDlg;
						ofn.lpstrFilter = _T("Executables (*.exe)\0*.exe\0\0");
						ofn.nFilterIndex = 1;
						ofn.lpstrFile = pszFilePath+1;
						ofn.nMaxFile = nLen;
						ofn.lpstrTitle = _T("Choose program to run");
						ofn.Flags = OFN_ENABLESIZING|OFN_NOCHANGEDIR
						            | OFN_PATHMUSTEXIST|OFN_EXPLORER|OFN_HIDEREADONLY|OFN_FILEMUSTEXIST;

						if (GetOpenFileName(&ofn))
						{
							LPCWSTR pszNewText = pszFilePath + 1;
							if (wcschr(pszFilePath, L' '))
							{
								pszFilePath[0] = L'"'; _wcscat_c(pszFilePath, nLen+3, L"\"");
								pszNewText = pszFilePath;
							}
							SetDlgItemText(hDlg, IDC_RESTART_CMD, pszNewText);
						}

						SafeFree(pszFilePath);
						return 1;
					}
					case IDC_CHOOSE_DIR:
					{
						BROWSEINFO bi = {ghWnd};
						wchar_t szFolder[MAX_PATH+1] = {0};
						GetDlgItemText(hDlg, IDC_STARTUP_DIR, szFolder, countof(szFolder));
						bi.pszDisplayName = szFolder;
						wchar_t szTitle[100];
						bi.lpszTitle = wcscpy(szTitle, L"Choose startup directory");
						bi.ulFlags = BIF_EDITBOX | BIF_RETURNONLYFSDIRS | BIF_VALIDATE;
						bi.lpfn = BrowseCallbackProc;
						bi.lParam = (LPARAM)szFolder;
						LPITEMIDLIST pRc = SHBrowseForFolder(&bi);

						if (pRc)
						{
							if (SHGetPathFromIDList(pRc, szFolder))
							{
								SetDlgItemText(hDlg, IDC_STARTUP_DIR, szFolder);
							}

							CoTaskMemFree(pRc);
						}

						return 1;
					}
					case cbRunAsAdmin:
					{
						// BCM_SETSHIELD = 5644
						BOOL bRunAs = SendDlgItemMessage(hDlg, cbRunAsAdmin, BM_GETCHECK, 0, 0);

						if (gOSVer.dwMajorVersion >= 6)
						{
							SendDlgItemMessage(hDlg, IDC_START, 5644/*BCM_SETSHIELD*/, 0, bRunAs);
						}

						if (bRunAs)
						{
							CheckRadioButton(hDlg, rbCurrentUser, rbAnotherUser, rbCurrentUser);
							CheckDlgButton(hDlg, cbRunAsRestricted, BST_UNCHECKED);
							RecreateDlgProc(hDlg, UM_USER_CONTROLS, 0, 0);
						}

						return 1;
					}
					case rbCurrentUser:
					case rbAnotherUser:
					case cbRunAsRestricted:
					{
						RecreateDlgProc(hDlg, UM_USER_CONTROLS, LOWORD(wParam), 0);
						return 1;
					}
					case IDC_START:
					{
						RConStartArgs* pArgs = pDlg->mp_Args;
						_ASSERTE(pArgs);
						SafeFree(pArgs->pszUserName);
						SafeFree(pArgs->pszDomain);

						//SafeFree(pArgs->pszUserPassword);
						if (SendDlgItemMessage(hDlg, rbAnotherUser, BM_GETCHECK, 0, 0))
						{
							pArgs->bRunAsRestricted = FALSE;
							pArgs->pszUserName = GetDlgItemText(hDlg, tRunAsUser);

							if (pArgs->pszUserName)
							{
								//pArgs->pszUserPassword = GetDlgItemText(hDlg, tRunAsPassword);
								// Попытаться проверить правильность введенного пароля и возможность запуска
								if (!pArgs->CheckUserToken(GetDlgItem(hDlg, tRunAsPassword)))
									return 1;
							}
						}
						else
						{
							pArgs->bRunAsRestricted = SendDlgItemMessage(hDlg, cbRunAsRestricted, BM_GETCHECK, 0, 0);
						}

						// Command
						// pszSpecialCmd мог быть передан аргументом - умолчание для строки ввода
						SafeFree(pArgs->pszSpecialCmd);

						// GetDlgItemText выделяет память через calloc
						pArgs->pszSpecialCmd = GetDlgItemText(hDlg, IDC_RESTART_CMD);

						if (pArgs->pszSpecialCmd)
							gpSet->HistoryAdd(pArgs->pszSpecialCmd);

						// StartupDir (может быть передан аргументом)
						SafeFree(pArgs->pszStartupDir);
						wchar_t* pszDir = GetDlgItemText(hDlg, IDC_STARTUP_DIR);
						wchar_t* pszExpand = (pszDir && wcschr(pszDir, L'%')) ? ExpandEnvStr(pszDir) : NULL;
						pArgs->pszStartupDir = pszExpand ? pszExpand : pszDir;
						if (pszExpand)
						{
							SafeFree(pszDir)
						}
						// Vista+ (As Admin...)
						pArgs->bRunAsAdministrator = SendDlgItemMessage(hDlg, cbRunAsAdmin, BM_GETCHECK, 0, 0);
						if (pArgs->aRecreate != cra_RecreateTab)
						{
							if (SendDlgItemMessage(hDlg, cbRunInNewWindow, BM_GETCHECK, 0, 0))
								pArgs->aRecreate = cra_CreateWindow;
							else
								pArgs->aRecreate = cra_CreateTab;
						}
						pDlg->mn_DlgRc = IDC_START;
						EndDialog(hDlg, IDC_START);
						return 1;
					}
					case IDC_TERMINATE:
						pDlg->mn_DlgRc = IDC_TERMINATE;
						EndDialog(hDlg, IDC_TERMINATE);
						return 1;
					case IDCANCEL:
						pDlg->mn_DlgRc = IDCANCEL;
						EndDialog(hDlg, IDCANCEL);
						return 1;
				}
			}

			break;
		default:
			return 0;
	}

	return 0;
}
Exemple #14
0
/*
List files in the local client folder and send the list to the File Client
*/
bool CFileServer::ListFileInDestinationFolder()
{
	try
	{
		//***Pan peng 2008-11-28
		RemoteFolderPath path;
		if (!m_pServerSocket->ReadExact(m_pServerSocket->GetWorkingSocket(), (char*)(&path), sizeof(RemoteFolderPath)))
			return false;

		//if(m_strReceivePath.Find(" 桌面") != -1)
		if(m_strReceivePath.Find(szDesktop_CH) != -1 && m_strReceivePath.Find(szDesktop_EN) != -1)
		{
			char strDesktop[MAX_PATH];
			LPITEMIDLIST pidl;
			SHGetSpecialFolderLocation(0, CSIDL_DESKTOP, &pidl);
			SHGetPathFromIDList(pidl, strDesktop);
			m_strReceivePath = strDesktop;
		}
		else
			m_strReceivePath = path.RemotePath;
		//end***
		CDestFolderHelper folderHelper;
		folderHelper.SetDestFolder(m_strReceivePath);
		FileCount structFileCount;

		if (folderHelper.IsDestFolderExist())
		{
			int nFileCount = 0;
			BasicFileInfoList* pFileList = folderHelper.GetFileListInDestFolder(&nFileCount);

			if (pFileList == NULL)
			{
				structFileCount.nFileCount = 0;
				return SendListFileResponseHeader(structFileCount);
			}
			else
			{
				structFileCount.nFileCount = nFileCount;
				SendListFileResponseHeader(structFileCount);

				bool bResult = SendLocalFileInfo(pFileList);

				while (pFileList != NULL)
				{
					BasicFileInfoList* pNext =  pFileList->pNext;
					delete pFileList;
					pFileList = pNext;
				}

				return bResult;
			}
		}
		else
		{
			structFileCount.nFileCount = 0;
			return SendListFileResponseHeader(structFileCount);
		}
	}
	catch(...)
	{
		if (gl_pLogger)
			gl_pLogger->log_info("CFileServer::ProcessFileHeader() unkown exception.");
	}
	return false;
}
Exemple #15
0
LRESULT CALLBACK CWinEventsWin32::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
  XBMC_Event newEvent;
  ZeroMemory(&newEvent, sizeof(newEvent));
  static HDEVNOTIFY hDeviceNotify;

  if (uMsg == WM_CREATE)
  {
    SetWindowLongPtr(hWnd, GWLP_USERDATA, (LONG)(((LPCREATESTRUCT)lParam)->lpCreateParams));
    DIB_InitOSKeymap();
    g_uQueryCancelAutoPlay = RegisterWindowMessage(TEXT("QueryCancelAutoPlay"));
    shcne.pidl = NULL;
    shcne.fRecursive = TRUE;
    long fEvents = SHCNE_DRIVEADD | SHCNE_DRIVEREMOVED | SHCNE_MEDIAREMOVED | SHCNE_MEDIAINSERTED;
    SHChangeNotifyRegister(hWnd, SHCNRF_ShellLevel | SHCNRF_NewDelivery, fEvents, WM_MEDIA_CHANGE, 1, &shcne);
    RegisterDeviceInterfaceToHwnd(USB_HID_GUID, hWnd, &hDeviceNotify);
    return 0;
  }

  m_pEventFunc = (PHANDLE_EVENT_FUNC)GetWindowLongPtr(hWnd, GWLP_USERDATA);
  if (!m_pEventFunc)
    return DefWindowProc(hWnd, uMsg, wParam, lParam);

  if(g_uQueryCancelAutoPlay != 0 && uMsg == g_uQueryCancelAutoPlay)
    return S_FALSE;

  switch (uMsg)
  {
    case WM_CLOSE:
    case WM_QUIT:
    case WM_DESTROY:
      newEvent.type = XBMC_QUIT;
      m_pEventFunc(newEvent);
      break;
    case WM_SHOWWINDOW:
      {
        bool active = g_application.m_AppActive;
        g_application.m_AppActive = wParam != 0;
        if (g_application.m_AppActive != active)
          g_Windowing.NotifyAppActiveChange(g_application.m_AppActive);
        CLog::Log(LOGDEBUG, __FUNCTION__"Window is %s", g_application.m_AppActive ? "shown" : "hidden");
      }
      break;
    case WM_ACTIVATE:
      {
        bool active = g_application.m_AppActive;
        if (HIWORD(wParam))
        {
          g_application.m_AppActive = false;
        }
        else
        {
          WINDOWPLACEMENT lpwndpl;
          lpwndpl.length = sizeof(lpwndpl);
          if (LOWORD(wParam) != WA_INACTIVE)
          {
            if (GetWindowPlacement(hWnd, &lpwndpl))
              g_application.m_AppActive = lpwndpl.showCmd != SW_HIDE;
          }
          else
          {
            g_application.m_AppActive = g_Windowing.WindowedMode();
          }
        }
        if (g_application.m_AppActive != active)
          g_Windowing.NotifyAppActiveChange(g_application.m_AppActive);
        CLog::Log(LOGDEBUG, __FUNCTION__"Window is %s", g_application.m_AppActive ? "active" : "inactive");
      }
      break;
    case WM_SETFOCUS:
    case WM_KILLFOCUS:
      g_application.m_AppFocused = uMsg == WM_SETFOCUS;
      g_Windowing.NotifyAppFocusChange(g_application.m_AppFocused);
      if (uMsg == WM_KILLFOCUS)
      {
        CStdString procfile;
        if (CWIN32Util::GetFocussedProcess(procfile))
          CLog::Log(LOGDEBUG, __FUNCTION__": Focus switched to process %s", procfile.c_str());
      }
      break;
    case WM_SYSKEYDOWN:
      switch (wParam)
      {
        case VK_F4: //alt-f4, default event quit.
          return(DefWindowProc(hWnd, uMsg, wParam, lParam));
        case VK_RETURN: //alt-return
          if ((lParam & REPEATED_KEYMASK) == 0)
            g_graphicsContext.ToggleFullScreenRoot();
          return 0;
      }
      //deliberate fallthrough
    case WM_KEYDOWN:
    {
      switch (wParam)
      {
        case VK_CONTROL:
          if ( lParam & EXTENDED_KEYMASK )
            wParam = VK_RCONTROL;
          else
            wParam = VK_LCONTROL;
          break;
        case VK_SHIFT:
          /* EXTENDED trick doesn't work here */
          if (GetKeyState(VK_LSHIFT) & 0x8000)
            wParam = VK_LSHIFT;
          else if (GetKeyState(VK_RSHIFT) & 0x8000)
            wParam = VK_RSHIFT;
          break;
        case VK_MENU:
          if ( lParam & EXTENDED_KEYMASK )
            wParam = VK_RMENU;
          else
            wParam = VK_LMENU;
          break;
      }
      XBMC_keysym keysym;
      TranslateKey(wParam, HIWORD(lParam), &keysym, 1);

      newEvent.type = XBMC_KEYDOWN;
      newEvent.key.keysym = keysym;
      m_pEventFunc(newEvent);
    }
    return(0);

    case WM_SYSKEYUP:
    case WM_KEYUP:
      {
      switch (wParam)
      {
        case VK_CONTROL:
          if ( lParam&EXTENDED_KEYMASK )
            wParam = VK_RCONTROL;
          else
            wParam = VK_LCONTROL;
          break;
        case VK_SHIFT:
          {
            uint32_t scanCodeL = MapVirtualKey(VK_LSHIFT, MAPVK_VK_TO_VSC);
            uint32_t scanCodeR = MapVirtualKey(VK_RSHIFT, MAPVK_VK_TO_VSC);
            uint32_t keyCode = (uint32_t)((lParam & 0xFF0000) >> 16);
            if (keyCode == scanCodeL)
              wParam = VK_LSHIFT;
            else if (keyCode == scanCodeR)
              wParam = VK_RSHIFT;
          }
          break;
        case VK_MENU:
          if ( lParam&EXTENDED_KEYMASK )
            wParam = VK_RMENU;
          else
            wParam = VK_LMENU;
          break;
      }
      XBMC_keysym keysym;
      TranslateKey(wParam, HIWORD(lParam), &keysym, 1);

      if (wParam == VK_SNAPSHOT)
        newEvent.type = XBMC_KEYDOWN;
      else
        newEvent.type = XBMC_KEYUP;
      newEvent.key.keysym = keysym;
      m_pEventFunc(newEvent);
    }
    return(0);
    case WM_APPCOMMAND: // MULTIMEDIA keys are mapped to APPCOMMANDS
    {
      CLog::Log(LOGDEBUG, "WinEventsWin32.cpp: APPCOMMAND %d", GET_APPCOMMAND_LPARAM(lParam));
      newEvent.appcommand.type = XBMC_APPCOMMAND;
      newEvent.appcommand.action = GET_APPCOMMAND_LPARAM(lParam);
      if (m_pEventFunc(newEvent))
        return TRUE;
      else
        return DefWindowProc(hWnd, uMsg, wParam, lParam);
    }
    case WM_GESTURENOTIFY:
    {
      OnGestureNotify(hWnd, lParam);
      return DefWindowProc(hWnd, WM_GESTURENOTIFY, wParam, lParam);
    }
    case WM_GESTURE:
    {
      OnGesture(hWnd, lParam);
      return 0;
    }
    case WM_SYSCHAR:
      if (wParam == VK_RETURN) //stop system beep on alt-return
        return 0;
      break;
    case WM_SETCURSOR:
      if (HTCLIENT != LOWORD(lParam))
        g_Windowing.ShowOSMouse(true);
      break;
    case WM_MOUSEMOVE:
      newEvent.type = XBMC_MOUSEMOTION;
      newEvent.motion.x = GET_X_LPARAM(lParam);
      newEvent.motion.y = GET_Y_LPARAM(lParam);
      newEvent.motion.state = 0;
      m_pEventFunc(newEvent);
      return(0);
    case WM_LBUTTONDOWN:
    case WM_MBUTTONDOWN:
    case WM_RBUTTONDOWN:
      newEvent.type = XBMC_MOUSEBUTTONDOWN;
      newEvent.button.state = XBMC_PRESSED;
      newEvent.button.x = GET_X_LPARAM(lParam);
      newEvent.button.y = GET_Y_LPARAM(lParam);
      newEvent.button.button = 0;
      if (uMsg == WM_LBUTTONDOWN) newEvent.button.button = XBMC_BUTTON_LEFT;
      else if (uMsg == WM_MBUTTONDOWN) newEvent.button.button = XBMC_BUTTON_MIDDLE;
      else if (uMsg == WM_RBUTTONDOWN) newEvent.button.button = XBMC_BUTTON_RIGHT;
      m_pEventFunc(newEvent);
      return(0);
    case WM_LBUTTONUP:
    case WM_MBUTTONUP:
    case WM_RBUTTONUP:
      newEvent.type = XBMC_MOUSEBUTTONUP;
      newEvent.button.state = XBMC_RELEASED;
      newEvent.button.x = GET_X_LPARAM(lParam);
      newEvent.button.y = GET_Y_LPARAM(lParam);
      newEvent.button.button = 0;
      if (uMsg == WM_LBUTTONUP) newEvent.button.button = XBMC_BUTTON_LEFT;
      else if (uMsg == WM_MBUTTONUP) newEvent.button.button = XBMC_BUTTON_MIDDLE;
      else if (uMsg == WM_RBUTTONUP) newEvent.button.button = XBMC_BUTTON_RIGHT;
      m_pEventFunc(newEvent);
      return(0);
    case WM_MOUSEWHEEL:
      {
        // SDL, which our events system is based off, sends a MOUSEBUTTONDOWN message
        // followed by a MOUSEBUTTONUP message.  As this is a momentary event, we just
        // react on the MOUSEBUTTONUP message, resetting the state after processing.
        newEvent.type = XBMC_MOUSEBUTTONDOWN;
        newEvent.button.state = XBMC_PRESSED;
        // the coordinates in WM_MOUSEWHEEL are screen, not client coordinates
        POINT point;
        point.x = GET_X_LPARAM(lParam);
        point.y = GET_Y_LPARAM(lParam);
        WindowFromScreenCoords(hWnd, &point);
        newEvent.button.x = (uint16_t)point.x;
        newEvent.button.y = (uint16_t)point.y;
        newEvent.button.button = GET_Y_LPARAM(wParam) > 0 ? XBMC_BUTTON_WHEELUP : XBMC_BUTTON_WHEELDOWN;
        m_pEventFunc(newEvent);
        newEvent.type = XBMC_MOUSEBUTTONUP;
        newEvent.button.state = XBMC_RELEASED;
        m_pEventFunc(newEvent);
      }
      return(0);
    case WM_SIZE:
      newEvent.type = XBMC_VIDEORESIZE;
      newEvent.resize.type = XBMC_VIDEORESIZE;
      newEvent.resize.w = GET_X_LPARAM(lParam);
      newEvent.resize.h = GET_Y_LPARAM(lParam);
      if (newEvent.resize.w * newEvent.resize.h)
        m_pEventFunc(newEvent);
      return(0);
    case WM_MEDIA_CHANGE:
      {
        // There may be multiple notifications for one event
        // There are also a few events we're not interested in, but they cause no harm
        // For example SD card reader insertion/removal
        long lEvent;
        PIDLIST_ABSOLUTE *ppidl;
        HANDLE hLock = SHChangeNotification_Lock((HANDLE)wParam, (DWORD)lParam, &ppidl, &lEvent);

        if (hLock)
        {
          char drivePath[MAX_PATH+1];
          if (!SHGetPathFromIDList(ppidl[0], drivePath))
            break;

          switch(lEvent)
          {
            case SHCNE_DRIVEADD:
            case SHCNE_MEDIAINSERTED:
              CLog::Log(LOGDEBUG, __FUNCTION__": Drive %s Media has arrived.", drivePath);
              if (GetDriveType(drivePath) == DRIVE_CDROM)
                g_application.getApplicationMessenger().OpticalMount(drivePath, true);
              else
                CWin32StorageProvider::SetEvent();
              break;

            case SHCNE_DRIVEREMOVED:
            case SHCNE_MEDIAREMOVED:
              CLog::Log(LOGDEBUG, __FUNCTION__": Drive %s Media was removed.", drivePath);
              if (GetDriveType(drivePath) == DRIVE_CDROM)
                g_application.getApplicationMessenger().OpticalUnMount(drivePath);
              else
                CWin32StorageProvider::SetEvent();
              break;
          }
          SHChangeNotification_Unlock(hLock);
        }
        break;
      }
    case WM_POWERBROADCAST:
      if (wParam==PBT_APMSUSPEND)
      {
        CLog::Log(LOGDEBUG,"WM_POWERBROADCAST: PBT_APMSUSPEND event was sent");
        CWin32PowerSyscall::SetOnSuspend();
      }
      else if(wParam==PBT_APMRESUMEAUTOMATIC)
      {
        CLog::Log(LOGDEBUG,"WM_POWERBROADCAST: PBT_APMRESUMEAUTOMATIC event was sent");
        CWin32PowerSyscall::SetOnResume();
      }
      break;
    case WM_DEVICECHANGE:
      {
        PDEV_BROADCAST_DEVICEINTERFACE b = (PDEV_BROADCAST_DEVICEINTERFACE) lParam;
        CStdString dbcc_name(b->dbcc_name);
        dbcc_name = CKeymapLoader::ParseWin32HIDName(b->dbcc_name);
        switch (wParam)
        {
          case DBT_DEVICEARRIVAL:
            CKeymapLoader().DeviceAdded(dbcc_name);
            break;
          case DBT_DEVICEREMOVECOMPLETE:
            CKeymapLoader().DeviceRemoved(dbcc_name);
            break;
          case DBT_DEVNODES_CHANGED:
            //CLog::Log(LOGDEBUG, "HID Device Changed");
            //We generally don't care about Change notifications, only need to know if a device is removed or added to rescan the device list
            break;
        }
        break;
      }
    case WM_PAINT:
      //some other app has painted over our window, mark everything as dirty
      g_windowManager.MarkDirty();
      break;
  }
  return(DefWindowProc(hWnd, uMsg, wParam, lParam));
}
// ************************************************************
// Возвращает текущий выбранный каталог в активном Проводнике.
// ************************************************************
lem::Path lem::Shell::GetCurrentFolder(void)
{
 #if (defined LEM_MSC && _MSC_VER<1300) || defined LEM_WIN98

 lem::Path res;
 return res;

 #else

 TCHAR g_szPath[MAX_PATH];
 TCHAR g_szItem[MAX_PATH];

 HWND hwndFind = GetForegroundWindow();

 #if LEM_DEBUGGING==1
  TCHAR wndTitle[261];
  GetWindowText( hwndFind, wndTitle, sizeof(wndTitle) );
 #endif


 g_szPath[0] = TEXT('\0');
 g_szItem[0] = TEXT('\0');

 IShellWindows *psw=NULL;
 if( SUCCEEDED(CoCreateInstance(CLSID_ShellWindows, NULL, CLSCTX_ALL, IID_IShellWindows, (void**)&psw)))
  {
   VARIANT v;
   V_VT(&v) = VT_I4;
   IDispatch *pdisp=NULL;
   BOOL fFound = FALSE;

   for( V_I4(&v) = 0; !fFound && psw->Item(v, &pdisp) == S_OK; V_I4(&v)++ )
    {
     IWebBrowserApp *pwba=NULL;
     HRESULT rc = pdisp->QueryInterface(IID_IWebBrowserApp, (void**)&pwba);

     if( SUCCEEDED(rc) )
      {
       HWND hwndWBA=NULL;
       rc = pwba->get_HWND((LONG_PTR*)&hwndWBA);

       if( SUCCEEDED(rc) && hwndWBA == hwndFind )
        {
         fFound = TRUE;
         IServiceProvider *psp=NULL;
         if( SUCCEEDED(pwba->QueryInterface(IID_IServiceProvider, (void**)&psp)) )
          {
           IShellBrowser *psb=NULL;
           if( SUCCEEDED(psp->QueryService(SID_STopLevelBrowser, IID_IShellBrowser, (void**)&psb)))
            {
             IShellView *psv=NULL;
             if( SUCCEEDED(psb->QueryActiveShellView(&psv)) )
              {
             IFolderView *pfv=NULL;
             if (SUCCEEDED(psv->QueryInterface(IID_IFolderView,
                                               (void**)&pfv))) {
               IPersistFolder2 *ppf2=NULL;
               if (SUCCEEDED(pfv->GetFolder(IID_IPersistFolder2,
                                            (void**)&ppf2))) {
                 LPITEMIDLIST pidlFolder=NULL;
                 if (SUCCEEDED(ppf2->GetCurFolder(&pidlFolder))) {
                   if (!SHGetPathFromIDList(pidlFolder, g_szPath))
                    {
                     //lstrcpyn(g_szPath, TEXT("<not a directory>"), MAX_PATH);
                    }
                   int iFocus=0;
                   if (SUCCEEDED(pfv->GetFocusedItem(&iFocus))) {
                     LPITEMIDLIST pidlItem=NULL;
                     if (SUCCEEDED(pfv->Item(iFocus, &pidlItem))) {
                       IShellFolder *psf=NULL;
                       if (SUCCEEDED(ppf2->QueryInterface(IID_IShellFolder,
                                                          (void**)&psf))) {
                         STRRET str;
                         if (SUCCEEDED(psf->GetDisplayNameOf(pidlItem,
                                                   SHGDN_INFOLDER,
                                                   &str))) {
                           StrRetToBuf(&str, pidlItem, g_szItem, MAX_PATH);
                         }
                         psf->Release();
                       }
                       CoTaskMemFree(pidlItem);
                     }
                   }
                   CoTaskMemFree(pidlFolder);
                 }
                 ppf2->Release();
               }
               pfv->Release();
             }
             psv->Release();
           }
           psb->Release();
         }
         psp->Release();
       }
     }
     pwba->Release();
   }
    pdisp->Release();
  }
  psw->Release();
 }

 lem::Path res(g_szPath);
 return res;
 #endif
}
Exemple #17
0
void    IBatchFreeType( HWND hWnd, const char *path )
{
    static plFontFreeType::Options info;

    if( DialogBoxParam( gInstance, MAKEINTRESOURCE( IDD_FREETYPEBATCH ), hWnd, FreeTypeBatchDlgProc, (LPARAM)&info ) == IDCANCEL )
        return;

    BROWSEINFO      bInfo;
    LPITEMIDLIST    itemList;
    LPMALLOC        shMalloc;
    static char     destPath[ MAX_PATH ] = "";

    memset( &bInfo, 0, sizeof( bInfo ) );
    bInfo.hwndOwner = hWnd;
    bInfo.pidlRoot = NULL;
    bInfo.pszDisplayName = destPath;
    bInfo.lpszTitle = "Select a path to write the P2F fonts to:";
    bInfo.ulFlags = BIF_EDITBOX;

    itemList = SHBrowseForFolder( &bInfo );
    if( itemList != NULL )
    {
        SHGetPathFromIDList( itemList, destPath );
        SHGetMalloc( &shMalloc );
        shMalloc->Free( itemList );
        shMalloc->Release();
    }
    else
        return;

    HWND dialog = CreateDialog( gInstance, MAKEINTRESOURCE( IDD_PROGRESS ), hWnd, ProgressWndProc );
    ShowWindow( dialog, SW_SHOW );
    EnableWindow( hWnd, false );
    plMyBDFCallback callback( dialog );

    callback.NumChars( sNumSizes );
    uint8_t i;
    for( i = 0; i < sNumSizes; i++ )
    {
        IMakeNewFont();
        plFontFreeType *ft2Convert = (plFontFreeType *)gFont;

        info.fSize = sSizeArray[ i ];
        if( !ft2Convert->ImportFreeType( path, &info, nil ) )
        {
            MessageBox( hWnd, "Failure converting TrueType file", "ERROR", MB_OK | MB_ICONEXCLAMATION );
            continue;
        }

        gFont->SetFace(sFontName);
        char fileName[ MAX_PATH ];
        sprintf( fileName, "%s\\%s-%d.p2f", destPath, gFont->GetFace(), gFont->GetSize() );
        hsUNIXStream stream;
        if( !stream.Open( fileName, "wb" ) )
            MessageBox( hWnd, "Can't open file for writing", "Error", MB_OK | MB_ICONEXCLAMATION );
        else
        {
            gFont->WriteRaw( &stream );
            stream.Close();
        }

        callback.CharDone();
    }

    DestroyWindow( dialog );
    EnableWindow( hWnd, true );
    IUpdateInfo( hWnd );
}
bool browse_for_dir(char *result)
{
	BROWSEINFO bi;
	LPITEMIDLIST pIDL;
	static char szFileName[MAX_PATH] = "";
	LPMALLOC pMem = NULL;
	char curr_folder[MAX_PATH] = "";
	
	ZeroMemory(&bi, sizeof(BROWSEINFO));

	GetCurrentDirectory(MAX_PATH, curr_folder);

	bi.hwndOwner    = FindWindow(NULL, "Imperial Alliance Launcher");//hDlg;
	bi.lpszTitle	= "Search for music:";
	bi.ulFlags		= BIF_RETURNONLYFSDIRS;
	bi.lpfn			= BrowseCallbackProc;
	bi.lParam       = (LPARAM)curr_folder;//DefaultLoadFolder;
			
	pIDL = SHBrowseForFolder(&bi);
			
	if(SHGetPathFromIDList(pIDL, szFileName))
	{
				
		strcpy(result, szFileName);
	/*if (PopFileSaveDlg(g_hwnd, PlaylistFilename, PlaylistSearchFolder) == TRUE)
				{
					SendMessage(GetDlgItem(g_hwnd, IDC_FILELIST), LB_RESETCONTENT, 0, 0);

					SearchFolder(DefaultLoadFolder);
							
					// use fcloseall() to make sure the file stream opened
					// while creating the playlist gets closed
					fcloseall();
				
					WritePrivateProfileString("Folders", "Search Folder",
						                    DefaultLoadFolder, ConfigFileName);
					WritePrivateProfileString("Playlist", "Last Used",
											PlaylistFilename, ConfigFileName);
				}
				else
					return TRUE;
											
				/*fp = fopen(ConfigFileName, "w");
				if (fp != NULL)
				{
					fprintf(fp, "%s", szFileName);

					fclose(fp);
				}*/
				
				//else
				//	MessageBox(hDlg, "Error writting to config file!",
				//				"EHMP3", MB_OK);
				

		if( SHGetMalloc(&pMem) == NOERROR )    
		{        
			pMem->Free(pIDL);        
			pMem->Release();
					
			return true;
		}

				
	}	

		return false;


/*LPITEMIDLIST  pidl;
	LPSHELLFOLDER pDesktopFolder;
	OLECHAR       olePath[MAX_PATH];
	ULONG         chEaten;
	HRESULT       hr;

	*result = '\0';
	// Get the path to the file we need to convert.
	GetCurrentDirectory(MAX_PATH, root);

	// Get a pointer to the Desktop's IShellFolder interface.
	if (FAILED(SHGetDesktopFolder(&pDesktopFolder)))
	{
		return true;
	}

	// IShellFolder::ParseDisplayName requires the file name be in Unicode.
	MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, root, -1, olePath, MAX_PATH);

	// Convert the path to an ITEMIDLIST.
	hr = pDesktopFolder->ParseDisplayName(hwnd, NULL, olePath, &chEaten, &pidl, NULL);
	if (FAILED(hr))
	{
		return true;
	}

	// pidl now contains a pointer to an ITEMIDLIST 

	// Browse for the file
	BROWSEINFO browse_info;

    browse_info.hwndOwner = hwnd; 
	browse_info.pidlRoot  = pidl; 
    browse_info.pszDisplayName = NULL;
    browse_info.lpszTitle = title; 
    browse_info.ulFlags = 0; 
    browse_info.lpfn = NULL; 
    browse_info.lParam = 0; 
    browse_info.iImage = 0; 

	LPITEMIDLIST dirs = SHBrowseForFolder(&browse_info); 

	//release the desktop folder object
    pDesktopFolder->Release();

	if(dirs == NULL) 
		return false;

	SHGetPathFromIDList(dirs, result); 

	return true;*/
}
bool CDVSPathsPPage::OnMessage(UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    switch(uMsg)
    {
        case WM_COMMAND:
        {
			switch(HIWORD(wParam))
			{
				case LBN_SELCHANGE:
					if((HWND)lParam == m_pathlist.m_hWnd)
					{
						int i = m_pathlist.GetCurSel();
						m_remove.EnableWindow(i >= 3 ? TRUE : FALSE);
						if(i >= 0)
						{
							CString path;
							m_pathlist.GetText(i, path);
							m_path.SetWindowText(path);
						}
						return(true);
					}
				break;

				case LBN_SELCANCEL:
					if((HWND)lParam == m_pathlist.m_hWnd)
					{
						m_remove.EnableWindow(FALSE);
						return(true);
					}
				break;

				case BN_CLICKED:
				{
					switch(LOWORD(wParam))
					{
						case IDC_BROWSE:
						{
							TCHAR pathbuff[MAX_PATH];

							BROWSEINFO bi;
							bi.hwndOwner = m_Dlg;
							bi.pidlRoot = NULL;
							bi.pszDisplayName = pathbuff;
							bi.lpszTitle = _T("");
							bi.ulFlags = BIF_RETURNONLYFSDIRS | BIF_EDITBOX | BIF_VALIDATE | BIF_USENEWUI;
							bi.lpfn = NULL;
							bi.lParam = 0;
							bi.iImage = 0; 

							LPITEMIDLIST iil;
							if(iil = SHBrowseForFolder(&bi))
							{
								SHGetPathFromIDList(iil, pathbuff);
								m_path.SetWindowText(pathbuff);
							}

							return(true);
						}
						break;

						case IDC_REMOVE:
						{
							int i = m_pathlist.GetCurSel();
							if(i >= 0)
							{
								m_pathlist.DeleteString(i);
								i = min(i, m_pathlist.GetCount()-1);
								if(i >= 0 && m_pathlist.GetCount() > 0)
								{
									m_pathlist.SetCurSel(i);
									m_remove.EnableWindow(i >= 3 ? TRUE : FALSE);
								}
							}

							return(true);
						}
						break;

						case IDC_ADD:
						{
							CString path;
							m_path.GetWindowText(path);
							if(!path.IsEmpty() && m_pathlist.FindString(-1, path) < 0)
								m_pathlist.AddString(path);

							return(true);
						}
						break;
					}
				}
				break;
			}
		}
		break;
	}

    return(false);
}
Exemple #20
0
LRESULT CALLBACK WndProc( HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam )
{
    if (def_deviceproc(hwnd, message, wparam, lparam))
        return 0;

    switch (message)
    {
    case WM_USER_FWATCHNOTIFY:
    {
        long eventid;
        PIDLIST_ABSOLUTE *rgpidl;
        HANDLE notify_lock = SHChangeNotification_Lock((HANDLE)wparam, (DWORD)lparam, &rgpidl, &eventid);
        if (notify_lock)
        {
            std::wstring srcpath;
            std::wstring dstpath;

            wchar_t buffer[MAX_PATH];
            if (rgpidl[0])
            {
                SHGetPathFromIDList(rgpidl[0], buffer);
                srcpath = buffer;
            }
            if (rgpidl[1])
            {
                SHGetPathFromIDList(rgpidl[1], buffer);
                dstpath = buffer;
            }

            if (eventid == SHCNE_UPDATEITEM && srcpath.length() > 0)
            {
                xui_global::add_fwatch(eventid, srcpath, dstpath);
            }
        }
        SHChangeNotification_Unlock(notify_lock);
    }
    break;
    case WM_CLOSE:
    {
        PostQuitMessage(0);
    }
    break;
    case WM_MOVE:
    {
        int movex = (int)(short)LOWORD(lparam) - WNDPOSX;
        int movey = (int)(short)HIWORD(lparam) - WNDPOSY;
        std::vector<xui_syswnd*> vec = xui_global::get_syswndall();
        for (u32 i = 0; i < vec.size(); ++i)
        {
            xui_syswnd* syswnd = vec[i];
            xui_window* wnd = syswnd->get_popupctrl();
            xui_method_ptrcall(wnd, set_owner	)(NULL);
            xui_method_ptrcall(wnd, set_renderx	)(wnd->get_renderx()-movex);
            xui_method_ptrcall(wnd, set_rendery	)(wnd->get_rendery()-movey);
            xui_method_ptrcall(wnd, set_owner	)(syswnd);
        }

        WNDPOSX   = (int)(short)LOWORD(lparam);
        WNDPOSY   = (int)(short)HIWORD(lparam);
    }
    break;
    case WM_SIZE:
    {
        RECT rect;
        GetClientRect(hwnd, &rect);
        int w = rect.right-rect.left;
        int h = rect.bottom-rect.top;
        if (xui_desktop::get_ins() && w > 0 && h > 0)
            xui_desktop::get_ins()->set_rendersz(xui_vector<s32>(w, h));

        WNDWIDTH  = (int)(short)LOWORD(lparam);
        WNDHEIGHT = (int)(short)HIWORD(lparam);
    }
    break;
    default:
        return DefWindowProc(hwnd, message, wparam, lparam);
    }

    return 0;
}
Exemple #21
0
LRESULT CALLBACK DlgWndProc(HWND hwnd,UINT uMsg,WPARAM wParam,LPARAM lParam)
{
	OPENFILENAME opfn;
	BROWSEINFO bi;
	TCHAR fn[512];
	TCHAR fn2[512];
	switch(uMsg)
	{
	case WM_COMMAND:
		switch((wParam<<16)>>16)
		{
		case IDC_BROWSEORI:
			memset(fn,0,512);
			memset(&opfn,0,sizeof(opfn));
			opfn.lStructSize =sizeof(opfn);
			opfn.hwndOwner =hwnd;
			opfn.lpstrFilter =TEXT("DAT文件(*.dat)\0*.dat\0\0");
			opfn.lpstrFile =fn;
			opfn.nMaxFile =512;
			opfn.Flags=OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST;
			if(::GetOpenFileName(&opfn))
			{
				::SetDlgItemText(hwnd,IDC_ORINAME,fn);
			}
			break;
		case IDC_RUN:
			if(::IsDlgButtonChecked(hwnd,IDC_RADIO_EXT)==BST_CHECKED)
			{
				::GetDlgItemText(hwnd,IDC_ORINAME,fn,512);
				if(Extract(fn)==-1)
					MessageBox(hwnd,TEXT("解包失败!"),TEXT("摔14"),MB_OK|MB_ICONERROR);
				else
					MessageBox(hwnd,TEXT("解包完成!"),TEXT("摔14"),MB_OK);
			}
			else
			{
				::GetDlgItemText(hwnd,IDC_NEWFOLDER,fn,512);
				::GetDlgItemText(hwnd,IDC_ORINAME,fn2,512);
				if(Compact(fn,fn2)==-1)
					MessageBox(hwnd,TEXT("封装失败!"),TEXT("摔14"),MB_OK|MB_ICONERROR);
				else
					MessageBox(hwnd,TEXT("封装完成!"),TEXT("摔14"),MB_OK);
			}
			break;
		case IDC_BROWSENEW:
			memset(&bi,0,sizeof (bi));
			bi.hwndOwner=hwnd;
			bi.pszDisplayName=fn;
			bi.lpszTitle=TEXT("选择文件夹");
			bi.ulFlags=BIF_USENEWUI;
			LPITEMIDLIST idl;
			idl=SHBrowseForFolder(&bi);
			if(idl==NULL)
				break;
			if(!SHGetPathFromIDList(idl,fn))
				break;
			::SetDlgItemText(hwnd,IDC_NEWFOLDER,fn);
			break;
		case IDC_RADIO_EXT:
			if(wParam>>16==BN_CLICKED)
			{
				ext_main:
				EnableWindow(GetDlgItem(hwnd,IDC_BROWSENEW),FALSE);
				EnableWindow(GetDlgItem(hwnd,IDC_NEWFOLDER),FALSE);
				SetDlgItemText(hwnd,IDC_STATIC1,TEXT("原始脚本(如scr.dat)"));
//				SetDlgItemText(hwnd,IDC_STATIC2,TEXT("待封包目录(如scr文件夹)"));
			}
			break;
		case IDC_RADIO_COM:
			if(wParam>>16==BN_CLICKED)
			{
				EnableWindow(GetDlgItem(hwnd,IDC_BROWSENEW),TRUE);
				EnableWindow(GetDlgItem(hwnd,IDC_NEWFOLDER),TRUE);
				SetDlgItemText(hwnd,IDC_STATIC1,TEXT("新脚本(如scr1.dat)"));
//				SetDlgItemText(hwnd,IDC_STATIC2,TEXT("待封包目录(如scr文件夹)"));
			}
			break;
		}
		break;
	case WM_INITDIALOG:
		g_hWinMain=hwnd;
		CheckDlgButton(hwnd,IDC_RADIO_EXT,BST_CHECKED);
		goto ext_main;
		break;
	case WM_CLOSE:
		EndDialog(hwnd,0);
	}
	return 0;
}
BOOL MainWindow::OpenProjData()
{
	RootDicomObj *DCMinfo = NULL;
	char filename[MAX_PATH];
	char projFolder[MAX_PATH];

	BROWSEINFO bi = {0};
	PIDLIST_ABSOLUTE pidl;

	WCHAR szDisplayName[MAX_PATH];
	WCHAR szTitle[] = L"Select a folder containing projection data.";

	HANDLE hFindFile;
	WCHAR szFileName[MAX_PATH];
	WIN32_FIND_DATA findData = {0};

	if(m_Recon && !m_ReconSaved)
		if(MessageBox(m_hwnd,
			L"Reconstruction has not been saved. Do you wish to continue?",
			L"WinCone CT",
			MB_ICONWARNING | MB_YESNO) == IDNO)
			return FALSE;

	bi.hwndOwner = m_hwnd;
	bi.pidlRoot = NULL;
	bi.pszDisplayName = szDisplayName;
	bi.lpszTitle = szTitle;
	bi.ulFlags = BIF_NEWDIALOGSTYLE | BIF_NONEWFOLDERBUTTON | BIF_RETURNONLYFSDIRS;
	bi.lpfn = NULL;

	if(!(pidl = SHBrowseForFolder(&bi)))
		return FALSE;

	SHGetPathFromIDList(pidl, szDisplayName);

	// do _findfirst() stuff with current directory
	StringCchPrintf(szFileName,MAX_PATH,L"%s\\%s",szDisplayName,L"1.3.6.1.4.1*");
	hFindFile = FindFirstFile(szFileName,&findData);

	if(hFindFile == INVALID_HANDLE_VALUE)
	{
		MessageBox(m_hwnd,
			L"The selected folder does not contain valid DICOM projection data.",
			L"Load Projection Data",
			MB_OK);
		return FALSE;
	}

	FindClose(hFindFile);

	sprintf_s(filename,sizeof(filename),"%S\\%S",szDisplayName,findData.cFileName);
	DCMinfo = new RootDicomObj(filename,true);
	// confirm that DICOM files are legit here

	if(m_Recon)
	{
		delete m_Recon;
		m_Recon = NULL;
	}
	if(m_Proj)
	{
		delete m_Proj;
		m_Proj = NULL;
	}

	// Update the current folder field
	SendMessage(m_hCurrentFolder,WM_SETTEXT,NULL,(LPARAM)szDisplayName);

	// Enable the reconstruction controls

	delete DCMinfo;

	WideCharToMultiByte(1251,WC_NO_BEST_FIT_CHARS,szDisplayName,MAX_PATH,projFolder,sizeof(projFolder),0,NULL);
	m_Proj = new Projection(projFolder);
	SendMessage(m_hProgress,PBM_SETRANGE,MAKEWPARAM(0,0),MAKELPARAM(0,m_Proj->GetNumProj()));

	return TRUE;
}
// Procedure function for the message history location page in the wizard
BOOL CALLBACK wlmDBProc(HWND hdlg, UINT message, WPARAM wParam, LPARAM lParam) {
	BOOL result = FALSE;

	switch(message) {
		// Message to initialize dialog
		case WM_INITDIALOG:
			TranslateDialogDefault(hdlg);
			{
				TCHAR *defaultPath;

				#ifdef _DEBUG
					defaultPath = replaceVariable(_T("C:\\Documents and Settings\\Very Crazy Dog\\My Documents\\我已接收的檔案\\Very Crazy Dog's Message History"));
				#else
					defaultPath = replaceVariable(_T("%USERPROFILE%\\My Received Files"));
				#endif			
				SetDlgItemText(hdlg, IDC_FOLDERNAME, defaultPath);
				mir_free(defaultPath);
			}
			result = TRUE;
			break;
		// Message when a button is pressed
		case WM_COMMAND:
			switch(LOWORD(wParam)) {
				case IDC_BROWSER:
					{
						BROWSEINFO binfo;
						LPITEMIDLIST pidl;

						ZeroMemory(&binfo, sizeof(binfo));
						binfo.hwndOwner = hdlg;
						binfo.ulFlags = BIF_USENEWUI | BIF_NONEWFOLDERBUTTON | BIF_RETURNONLYFSDIRS;
						binfo.lpszTitle = TranslateT("Please select the Windows Live Messenger message history directory:");
						pidl = SHBrowseForFolder(&binfo);
						if(pidl != NULL) {
							// Get the name of the folder
							TCHAR path[MAX_PATH];

							if (SHGetPathFromIDList(pidl, path)) {
								SetDlgItemText(hdlg, IDC_FOLDERNAME, path);
							}
							GlobalFree(pidl);
						}
					}
					break;
				case IDC_BACK:
					PostMessage(GetParent(hdlg), WIZM_GOTOPAGE, IDD_IMPORTACC, (LPARAM)importAccountPageProc);
					break;
				case IDOK:
					{
						TCHAR path[MAX_PATH];
						UINT pathLen;
						TCHAR *realPath;

						pathLen = GetDlgItemText(hdlg, IDC_FOLDERNAME, path, SIZEOF(path));
						_tcscat_s(path, MAX_PATH, _T("\\MessageLog.xsl"));
						realPath = replaceVariable(path);
						if(_taccess_s(realPath, 4)) {
							MessageBox(hdlg, 
								TranslateT("File 'MessageLog.xsl' is missing.\r\nIs this a Windows Live Messenger message history folder?"), 
								TranslateT("WLM History Importer"), MB_OK | MB_ICONINFORMATION);
						}
						else {
							// Remove the appended file name
							if(pathLen <= MAX_PATH) {
								path[pathLen] = '\0';
							}
							mir_free(realPath);
							realPath = replaceVariable(path);
							_tcscpy_s(importFolderPath, MAX_PATH, realPath);
							_tcscat_s(importFolderPath, MAX_PATH, _T("\\"));
							PostMessage(GetParent(hdlg), WIZM_GOTOPAGE, IDD_OPTIONS, (LPARAM)wlmOptionsPageProc);
						}
						mir_free(realPath);
					}
					break;
				case IDCANCEL:
					PostMessage(GetParent(hdlg), WM_CLOSE, 0, 0);
					break;
			}
			break;
	}
	return result;
}
Exemple #24
0
INT_PTR CALLBACK DlgProcOptions(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
	TCHAR folder_buff[MAX_PATH] = { 0 };

	switch (msg) {
	case WM_INITDIALOG:
		TranslateDialogDefault(hwndDlg);
		memcpy(&new_options, &options, sizeof(Options));

		if (ServiceExists(MS_FOLDERS_GET_PATH)) {
			ShowWindow(GetDlgItem(hwndDlg, IDC_ED_FOLDER), SW_HIDE);
			ShowWindow(GetDlgItem(hwndDlg, IDC_BUT_BROWSE), SW_HIDE);
			ShowWindow(GetDlgItem(hwndDlg, IDC_LNK_FOLDERS), SW_SHOW);
		}
		else {
			TCHAR tszTooltipText[4096];
			mir_sntprintf(tszTooltipText, _countof(tszTooltipText), _T("%s - %s\n%s - %s\n%s - %s\n%s - %s\n%s - %s\n%s - %s\n%s - %s\n%s - %s\n%s - %s"),
				_T("%miranda_path%"), TranslateT("path to Miranda root folder"),
				_T("%miranda_profilesdir%"), TranslateT("path to folder containing Miranda profiles"),
				_T("%miranda_profilename%"), TranslateT("name of current Miranda profile (filename, without extension)"),
				_T("%miranda_userdata%"), TranslateT("will return parsed string %miranda_profilesdir%\\%miranda_profilename%"),
				_T("%appdata%"), TranslateT("same as environment variable %APPDATA% for currently logged-on Windows user"),
				_T("%username%"), TranslateT("username for currently logged-on Windows user"),
				_T("%mydocuments%"), TranslateT("\"My Documents\" folder for currently logged-on Windows user"),
				_T("%desktop%"), TranslateT("\"Desktop\" folder for currently logged-on Windows user"),
				_T("%xxxxxxx%"), TranslateT("any environment variable defined in current Windows session (like %systemroot%, %allusersprofile%, etc.)")
				);
			hPathTip = CreateToolTip(GetDlgItem(hwndDlg, IDC_ED_FOLDER), tszTooltipText, TranslateT("Variables"));
		}

		SetDlgState(hwndDlg);

		SendDlgItemMessage(hwndDlg, IDC_PT, CB_ADDSTRING, 0, (LPARAM)TranslateT("days"));
		SendDlgItemMessage(hwndDlg, IDC_PT, CB_ADDSTRING, 0, (LPARAM)TranslateT("hours"));
		SendDlgItemMessage(hwndDlg, IDC_PT, CB_ADDSTRING, 0, (LPARAM)TranslateT("minutes"));
		switch (new_options.period_type) {
		case PT_DAYS: SendDlgItemMessage(hwndDlg, IDC_PT, CB_SETCURSEL, 0, 0); break;
		case PT_HOURS: SendDlgItemMessage(hwndDlg, IDC_PT, CB_SETCURSEL, 1, 0); break;
		case PT_MINUTES: SendDlgItemMessage(hwndDlg, IDC_PT, CB_SETCURSEL, 2, 0); break;
		}

		if (hPathTip)
			SetTimer(hwndDlg, 0, 3000, NULL);
		return TRUE;

	case WM_COMMAND:
		if (HIWORD(wParam) == EN_CHANGE && (HWND)lParam == GetFocus()) {
			switch (LOWORD(wParam)) {
			case IDC_ED_PERIOD:
			case IDC_ED_FOLDER:
			case IDC_ED_NUMBACKUPS:
				SendMessage(GetParent(hwndDlg), PSM_CHANGED, 0, 0);
			}
		}
		if (HIWORD(wParam) == CBN_SELCHANGE)
			SendMessage(GetParent(hwndDlg), PSM_CHANGED, 0, 0);

		if (HIWORD(wParam) == BN_CLICKED) {
			switch (LOWORD(wParam)) {
			case IDC_RAD_DISABLED:
				if (IsDlgButtonChecked(hwndDlg, IDC_RAD_DISABLED))
					new_options.backup_types = BT_DISABLED;

				SetDlgState(hwndDlg);
				SendMessage(GetParent(hwndDlg), PSM_CHANGED, 0, 0);
				break;

			case IDC_RAD_START:
				if (IsDlgButtonChecked(hwndDlg, IDC_RAD_START))
					new_options.backup_types |= BT_START;
				else
					new_options.backup_types &= ~BT_START;
				SetDlgState(hwndDlg);
				SendMessage(GetParent(hwndDlg), PSM_CHANGED, 0, 0);
				break;

			case IDC_RAD_EXIT:
				if (IsDlgButtonChecked(hwndDlg, IDC_RAD_EXIT))
					new_options.backup_types |= BT_EXIT;
				else
					new_options.backup_types &= ~BT_EXIT;
				SetDlgState(hwndDlg);
				SendMessage(GetParent(hwndDlg), PSM_CHANGED, 0, 0);
				break;

			case IDC_RAD_PERIODIC:
				if (IsDlgButtonChecked(hwndDlg, IDC_RAD_PERIODIC))
					new_options.backup_types |= BT_PERIODIC;
				else
					new_options.backup_types &= ~BT_PERIODIC;
				SetDlgState(hwndDlg);
				SendMessage(GetParent(hwndDlg), PSM_CHANGED, 0, 0);
				break;

			case IDC_BUT_BROWSE:
			{
				BROWSEINFO bi;
				bi.hwndOwner = hwndDlg;
				bi.pidlRoot = 0;
				bi.pszDisplayName = folder_buff;
				bi.lpszTitle = TranslateT("Select backup folder");
				bi.ulFlags = BIF_NEWDIALOGSTYLE;
				bi.lpfn = BrowseProc;
				bi.lParam = 0;
				bi.iImage = 0;

				LPCITEMIDLIST pidl = SHBrowseForFolder(&bi);
				if (pidl != 0) {
					SHGetPathFromIDList(pidl, folder_buff);

					SetDlgItemText(hwndDlg, IDC_ED_FOLDER, folder_buff);

					SendMessage(GetParent(hwndDlg), PSM_CHANGED, 0, 0);

					CoTaskMemFree((void *)pidl);
				}
				break;
			}
			case IDC_BUT_NOW:
				BackupStart(NULL);
				break;
			case IDC_CHK_NOPROG:
				new_options.disable_progress = IsDlgButtonChecked(hwndDlg, IDC_CHK_NOPROG);
				SendMessage(GetParent(hwndDlg), PSM_CHANGED, 0, 0);
				break;
			case IDC_CHK_NOPOPUP:
				new_options.disable_popups = IsDlgButtonChecked(hwndDlg, IDC_CHK_NOPOPUP);
				SendMessage(GetParent(hwndDlg), PSM_CHANGED, 0, 0);
				break;
			case IDC_CHK_USEZIP:
				new_options.use_zip = IsDlgButtonChecked(hwndDlg, IDC_CHK_USEZIP);
				SendMessage(GetParent(hwndDlg), PSM_CHANGED, 0, 0);
				break;
			case IDC_LNK_FOLDERS:
			{
				OPENOPTIONSDIALOG ood = { 0 };
				ood.cbSize = sizeof(ood);
				ood.pszGroup = "Customize";
				ood.pszPage = "Folders";
				Options_Open(&ood);
				break;
			}
			}
		}
		break;

	case WM_TIMER:
		if (IsWindow(hPathTip))
			KillTimer(hPathTip, 4); // It will prevent tooltip autoclosing
		break;

	case WM_NOTIFY:
		if (((LPNMHDR)lParam)->code == PSN_APPLY) {
			TCHAR buff[10];
			GetDlgItemText(hwndDlg, IDC_ED_PERIOD, buff, _countof(buff));
			new_options.period = _ttoi(buff);
			GetDlgItemText(hwndDlg, IDC_ED_NUMBACKUPS, buff, _countof(buff));
			new_options.num_backups = _ttoi(buff);

			switch (SendDlgItemMessage(hwndDlg, IDC_PT, CB_GETCURSEL, 0, 0)) {
			case 0: new_options.period_type = PT_DAYS; break;
			case 1: new_options.period_type = PT_HOURS; break;
			case 2: new_options.period_type = PT_MINUTES; break;
			}

			GetDlgItemText(hwndDlg, IDC_ED_FOLDER, folder_buff, _countof(folder_buff));
			{
				TCHAR backupfolder[MAX_PATH] = { 0 };
				BOOL folder_ok = TRUE;
				TCHAR *tmp = Utils_ReplaceVarsT(folder_buff);

				if (mir_tstrlen(tmp) >= 2 && tmp[1] == ':')
					_tcsncpy_s(backupfolder, tmp, _TRUNCATE);
				else
					mir_sntprintf(backupfolder, _countof(backupfolder), _T("%s\\%s"), profilePath, tmp);
				mir_free(tmp);

				int err = CreateDirectoryTreeT(backupfolder);
				if (err != ERROR_ALREADY_EXISTS && err != 0) {
					TCHAR msg_buff[512];
					FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, 0, err, 0, msg_buff, 512, 0);
					MessageBox(0, msg_buff, TranslateT("Error creating backup folder"), MB_OK | MB_ICONERROR);
					folder_ok = FALSE;
				}

				if (folder_ok) {
					_tcsncpy_s(new_options.folder, folder_buff, _TRUNCATE);
					memcpy(&options, &new_options, sizeof(Options));
					SaveOptions();
				}
				else {
					memcpy(&new_options, &options, sizeof(Options));
					SetDlgState(hwndDlg);
				}
			}
			return TRUE;

		}
		break;

	case WM_DESTROY:
		if (hPathTip) {
			KillTimer(hwndDlg, 0);
			DestroyWindow(hPathTip);
			hPathTip = 0;
		}
		return FALSE;
	}

	return FALSE;
}
Exemple #25
0
INT_PTR CALLBACK CDialogPackage::SelectFolderDlgProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    switch (uMsg)
    {
    case WM_INITDIALOG:
    {
        EnableThemeDialogTexture(hWnd, ETDT_ENABLETAB);
        c_Dialog->SetDialogFont(hWnd);

        std::wstring* existingPath = (std::wstring*)lParam;
        SetWindowLongPtr(hWnd, GWLP_USERDATA, lParam);

        *existingPath += L'*';
        WIN32_FIND_DATA fd;
        HANDLE hFind = FindFirstFileEx(existingPath->c_str(), FindExInfoStandard, &fd, FindExSearchNameMatch, NULL, 0);
        existingPath->pop_back();

        if (hFind != INVALID_HANDLE_VALUE)
        {
            const WCHAR* folder = PathFindFileName(existingPath->c_str());

            HWND item = GetDlgItem(hWnd, IDC_PACKAGESELECTFOLDER_EXISTING_RADIO);
            std::wstring text = L"Add folder from ";
            text.append(folder, wcslen(folder) - 1);
            text += L':';
            SetWindowText(item, text.c_str());
            Button_SetCheck(item, BST_CHECKED);

            item = GetDlgItem(hWnd, IDC_PACKAGESELECTFOLDER_EXISTING_COMBO);

            do
            {
                if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY &&
                        !(fd.cFileName[0] == L'.' && (!fd.cFileName[1] || fd.cFileName[1] == L'.' && !fd.cFileName[2])) &&
                        wcscmp(fd.cFileName, L"Backup") != 0 &&
                        wcscmp(fd.cFileName, L"@Backup") != 0)
                {
                    ComboBox_InsertString(item, -1, fd.cFileName);
                }
            }
            while (FindNextFile(hFind, &fd));

            ComboBox_SetCurSel(item, 0);

            FindClose(hFind);
        }
    }
    break;

    case WM_COMMAND:
        switch (LOWORD(wParam))
        {
        case IDC_PACKAGESELECTFOLDER_EXISTING_RADIO:
        {
            HWND item = GetDlgItem(hWnd, IDC_PACKAGESELECTFOLDER_EXISTING_COMBO);
            EnableWindow(item, TRUE);
            int sel = ComboBox_GetCurSel(item);
            item = GetDlgItem(hWnd, IDC_PACKAGESELECTFOLDER_CUSTOM_EDIT);
            EnableWindow(item, FALSE);
            item = GetDlgItem(hWnd, IDC_PACKAGESELECTFOLDER_CUSTOMBROWSE_BUTTON);
            EnableWindow(item, FALSE);

            item = GetDlgItem(hWnd, IDOK);
            EnableWindow(item, sel != -1);
        }
        break;

        case IDC_PACKAGESELECTFOLDER_CUSTOM_RADIO:
        {
            HWND item = GetDlgItem(hWnd, IDC_PACKAGESELECTFOLDER_EXISTING_COMBO);
            EnableWindow(item, FALSE);
            item = GetDlgItem(hWnd, IDC_PACKAGESELECTFOLDER_CUSTOM_EDIT);
            EnableWindow(item, TRUE);
            item = GetDlgItem(hWnd, IDC_PACKAGESELECTFOLDER_CUSTOMBROWSE_BUTTON);
            EnableWindow(item, TRUE);

            SendMessage(hWnd, WM_COMMAND, MAKEWPARAM(IDC_PACKAGESELECTFOLDER_CUSTOM_EDIT, EN_CHANGE), 0);
        }
        break;

        case IDC_PACKAGESELECTFOLDER_CUSTOM_EDIT:
            if (HIWORD(wParam) == EN_CHANGE)
            {
                WCHAR buffer[MAX_PATH];
                int len = Edit_GetText((HWND)lParam, buffer, MAX_PATH);

                // Disable Add button if invalid directory
                DWORD attributes = GetFileAttributes(buffer);
                BOOL state = (attributes != INVALID_FILE_ATTRIBUTES &&
                              attributes & FILE_ATTRIBUTE_DIRECTORY);
                EnableWindow(GetDlgItem(hWnd, IDOK), state);
            }
            break;

        case IDC_PACKAGESELECTFOLDER_CUSTOMBROWSE_BUTTON:
        {
            WCHAR buffer[MAX_PATH];
            BROWSEINFO bi = {0};
            bi.hwndOwner = hWnd;
            bi.ulFlags = BIF_USENEWUI | BIF_NONEWFOLDERBUTTON | BIF_RETURNONLYFSDIRS;

            PIDLIST_ABSOLUTE pidl = SHBrowseForFolder(&bi);
            if (pidl && SHGetPathFromIDList(pidl, buffer))
            {
                HWND item = GetDlgItem(hWnd, IDC_PACKAGESELECTFOLDER_CUSTOM_EDIT);
                SetWindowText(item, buffer);
                CoTaskMemFree(pidl);
            }
        }
        break;

        case IDOK:
        {
            WCHAR buffer[MAX_PATH];
            HWND item = GetDlgItem(hWnd, IDC_PACKAGESELECTFOLDER_EXISTING_RADIO);
            bool existing = Button_GetCheck(item) == BST_CHECKED;

            item = GetDlgItem(hWnd, existing ? IDC_PACKAGESELECTFOLDER_EXISTING_COMBO : IDC_PACKAGESELECTFOLDER_CUSTOM_EDIT);
            GetWindowText(item, buffer, _countof(buffer));

            std::wstring* result = (std::wstring*)GetWindowLongPtr(hWnd, GWLP_USERDATA);

            if (existing)
            {
                *result += buffer;
            }
            else
            {
                *result = buffer;
            }
            *result += L'\\';

            EndDialog(hWnd, 1);
        }
        }
        break;

    case WM_CLOSE:
        EndDialog(hWnd, 0);
        break;

    default:
        return FALSE;
    }

    return TRUE;
}
Exemple #26
0
void GetDrives (CDriveArray &array)
{
	array.clear ();

	IShellFolder   *psfDesktop;

	SHGetDesktopFolder(&psfDesktop);
	if(psfDesktop == NULL)
		return;
	
	LPITEMIDLIST   pidlMyComputer;

	SHGetSpecialFolderLocation(NULL, CSIDL_DRIVES, &pidlMyComputer);

	if(pidlMyComputer == NULL)
	{
		psfDesktop->Release();
		return;
	}
	
	IShellFolder   *psfMyComputer;

	psfDesktop->BindToObject(pidlMyComputer, NULL, IID_IShellFolder, (LPVOID*)&psfMyComputer);
	
	if(psfMyComputer)
	 {
			IEnumIDList* pEnum;
			if(SUCCEEDED(psfMyComputer->EnumObjects(NULL, SHCONTF_FOLDERS|SHCONTF_INCLUDEHIDDEN, &pEnum)))
			{
				ITEMIDLIST* pidl;
				DWORD  dwFetched = 1;
				TCHAR  path[MAX_PATH];

				while(SUCCEEDED(pEnum->Next(1, &pidl, &dwFetched)) && dwFetched)
				{
					SHFILEINFO     sfi;	
					
					//LPITEMIDLIST pidl_full = Pidl_Concatenate (pidlMyComputer, pidl);
					LPITEMIDLIST pidl_full = ILCombine (pidlMyComputer, pidl);					
					SHGetPathFromIDList (pidl_full, path);

					UINT nType = GetDriveType( path);
				//	if( DRIVE_REMOVABLE < nType && nType <= DRIVE_RAMDISK )
					if( nType != DRIVE_UNKNOWN && nType != DRIVE_NO_ROOT_DIR )
					if(SHGetFileInfo((LPCTSTR)pidl_full, 0, &sfi, sizeof(sfi), SHGFI_PIDL | SHGFI_DISPLAYNAME | SHGFI_TYPENAME | SHGFI_SYSICONINDEX | SHGFI_SMALLICON | SHGFI_LINKOVERLAY))
					{
						CDriveInfo info;
						info.m_Name = sfi.szDisplayName;
						info.m_Path = path;
						info.m_Type = sfi.szTypeName;
						info.m_nImage = sfi.iIcon;
						info.m_nType = nType;
						
						DWORD SectorsPerCluster;     // sectors per cluster
						DWORD BytesPerSector;        // bytes per sector
						DWORD NumberOfFreeClusters;  // free clusters
						DWORD TotalNumberOfClusters; // total clusters
					//	TRACE (L"%s %s\n", sfi.szDisplayName, path);		
						if (nType != DRIVE_REMOVABLE )
						if (GetDiskFreeSpace (path, &SectorsPerCluster, &BytesPerSector, &NumberOfFreeClusters, &TotalNumberOfClusters))
							{	
									DWORD BytesPerCluster = BytesPerSector * SectorsPerCluster;								
									info.m_FreeSpace = UInt32x32To64(NumberOfFreeClusters, BytesPerCluster);
									info.m_TotalSize= UInt32x32To64(TotalNumberOfClusters, BytesPerCluster);
							}
						array.push_back (info);
					}
				}
				pEnum->Release ();
			}
		 psfMyComputer->Release();
	 }

	
	CoTaskMemFree(pidlMyComputer);
	
	psfDesktop->Release();    	
}
Exemple #27
0
QString Q3FileDialog::winGetExistingDirectory(const QString& initialDirectory,
        QWidget *parent,
        const char* /*name*/,
        const QString& caption)
{
#ifndef Q_OS_WINCE
    QString currentDir = QDir::currentDirPath();
    QString result;
    if (parent)
        parent = parent->window();
    else
        parent = qApp->activeWindow();
    QString title = caption;
    if (title.isNull())
        title = tr("Select a Directory");

    if (parent) {
        QEvent e(QEvent::WindowBlocked);
        QApplication::sendEvent(parent, &e);
        QApplicationPrivate::enterModal(parent);
    }

    QString initDir = QDir::toNativeSeparators(initialDirectory);
    wchar_t path[MAX_PATH];
    wchar_t initPath[MAX_PATH];
    initPath[0] = 0;
    path[0] = 0;
    tTitle = title;
    BROWSEINFO bi;
    bi.hwndOwner = (parent ? parent->winId() : 0);
    bi.pidlRoot = NULL;
    bi.lpszTitle = (wchar_t*)tTitle.utf16();
    bi.pszDisplayName = initPath;
    bi.ulFlags = BIF_RETURNONLYFSDIRS | BIF_STATUSTEXT | BIF_NEWDIALOGSTYLE;
    bi.lpfn = winGetExistDirCallbackProc;
    bi.lParam = Q_ULONG(&initDir);
    LPITEMIDLIST pItemIDList = SHBrowseForFolder(&bi);
    if (pItemIDList) {
        SHGetPathFromIDList(pItemIDList, path);
        IMalloc *pMalloc;
        if (SHGetMalloc(&pMalloc) != NOERROR)
            result.clear();
        else {
            pMalloc->Free(pItemIDList);
            pMalloc->Release();
            result = QString::fromWCharArray(path);
        }
    } else
        result.clear();
    tTitle.clear();

    if (parent) {
        QApplicationPrivate::leaveModal(parent);
        QEvent e(QEvent::WindowUnblocked);
        QApplication::sendEvent(parent, &e);
    }

    if (!result.isEmpty())
        result.replace(QLatin1Char('\\'), QLatin1Char('/'));
    return result;
#else
    return QString();
#endif
}
Exemple #28
0
static INT_PTR CALLBACK DefInpProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam)
{
	int var;
	static bool chOk;

	switch (Msg) {
		case WM_INITDIALOG: {
			chOk = false;

			// Setup edit controls values (ROMs Paths)
			for(int x = 0; x < 8; x++) {
				SetDlgItemText(hDlg, IDC_ROMSDIR_EDIT1 + x, szAppRomPaths[x]);
			}

			// Setup the tabs
			hTabControl = GetDlgItem(hDlg, IDC_ROMPATH_TAB);

			TC_ITEM tcItem; 
			tcItem.mask = TCIF_TEXT;

			UINT idsString[8] = { IDS_ROMPATH_1,IDS_ROMPATH_2,IDS_ROMPATH_3,IDS_ROMPATH_4,IDS_ROMPATH_5,IDS_ROMPATH_6,IDS_ROMPATH_7,IDS_ROMPATH_8 };

			for(int nIndex = 0; nIndex < 8; nIndex++) {
				tcItem.pszText = FBALoadStringEx(hAppInst, idsString[nIndex], true);
				TabCtrl_InsertItem(hTabControl, nIndex, &tcItem);
			}

			int TabPage = TabCtrl_GetCurSel(hTabControl);
			
			// hide all controls excluding the selected controls
			for(int x = 0; x < 8; x++) {
				if(x != TabPage) {
					ShowWindow(GetDlgItem(hDlg, IDC_ROMSDIR_BR1 + x), SW_HIDE);		// browse buttons
					ShowWindow(GetDlgItem(hDlg, IDC_ROMSDIR_EDIT1 + x), SW_HIDE);	// edit controls
				}
			}

			// Show the proper controls
			ShowWindow(GetDlgItem(hDlg, IDC_ROMSDIR_BR1 + TabPage), SW_SHOW);		// browse buttons
			ShowWindow(GetDlgItem(hDlg, IDC_ROMSDIR_EDIT1 + TabPage), SW_SHOW);		// edit controls

			UpdateWindow(hDlg);

			WndInMid(hDlg, hParent);
			SetFocus(hDlg);											// Enable Esc=close
			break;
		}
		case WM_NOTIFY: {
			NMHDR* pNmHdr = (NMHDR*)lParam;

			if (pNmHdr->code == TCN_SELCHANGE) {

				int TabPage = TabCtrl_GetCurSel(hTabControl);
				
				// hide all controls excluding the selected controls
				for(int x = 0; x < 8; x++) {
					if(x != TabPage) {
						ShowWindow(GetDlgItem(hDlg, IDC_ROMSDIR_BR1 + x), SW_HIDE);		// browse buttons
						ShowWindow(GetDlgItem(hDlg, IDC_ROMSDIR_EDIT1 + x), SW_HIDE);	// edit controls
					}
				}

				// Show the proper controls
				ShowWindow(GetDlgItem(hDlg, IDC_ROMSDIR_BR1 + TabPage), SW_SHOW);		// browse buttons
				ShowWindow(GetDlgItem(hDlg, IDC_ROMSDIR_EDIT1 + TabPage), SW_SHOW);		// edit controls
				
				UpdateWindow(hDlg);

				return FALSE;
			}
			break;
		}
		case WM_COMMAND: {
			LPMALLOC pMalloc = NULL;
			BROWSEINFO bInfo;
			ITEMIDLIST* pItemIDList = NULL;
			TCHAR buffer[MAX_PATH];

			if (LOWORD(wParam) == IDOK) {

				for (int i = 0; i < 8; i++) {
//					if (GetDlgItemText(hDlg, IDC_ROMSDIR_EDIT1 + i, buffer, sizeof(buffer)) && lstrcmp(szAppRomPaths[i], buffer)) {
					GetDlgItemText(hDlg, IDC_ROMSDIR_EDIT1 + i, buffer, sizeof(buffer));
					if (lstrcmp(szAppRomPaths[i], buffer)) chOk = true;
					lstrcpy(szAppRomPaths[i], buffer);
//					}
				}

				SendMessage(hDlg, WM_CLOSE, 0, 0);
				break;
			} else {
				if (LOWORD(wParam) >= IDC_ROMSDIR_BR1 && LOWORD(wParam) <= IDC_ROMSDIR_BR8) {
					var = IDC_ROMSDIR_EDIT1 + LOWORD(wParam) - IDC_ROMSDIR_BR1;
				} else {
					if (HIWORD(wParam) == BN_CLICKED && LOWORD(wParam) == IDCANCEL) {
						SendMessage(hDlg, WM_CLOSE, 0, 0);
					}
					break;
				}
			}

		    SHGetMalloc(&pMalloc);

			memset(&bInfo, 0, sizeof(bInfo));
			bInfo.hwndOwner = hDlg;
			bInfo.pszDisplayName = buffer;
			bInfo.lpszTitle = FBALoadStringEx(hAppInst, IDS_ROMS_SELECT_DIR, true);
			bInfo.ulFlags = BIF_EDITBOX | BIF_RETURNONLYFSDIRS;

			pItemIDList = SHBrowseForFolder(&bInfo);

			if (pItemIDList) {
				if (SHGetPathFromIDList(pItemIDList, buffer)) {
					int strLen = _tcslen(buffer);
					if (strLen) {
						if (buffer[strLen - 1] != _T('\\')) {
							buffer[strLen] = _T('\\');
							buffer[strLen + 1] = _T('\0');
						}
						SetDlgItemText(hDlg, var, buffer);
					}
				}
				pMalloc->Free(pItemIDList);
			}
			pMalloc->Release();

			break;
		}
		case WM_CLOSE: {
			hParent = NULL;
			EndDialog(hDlg, 0);
			if (chOk) {
				bRescanRoms = true;
				CreateROMInfo(hDlg);
			}
		}
	}

	return 0;
}
// 创建一个快捷方式
BOOL CreateDesktopShotCut(tstring strName, tstring strSourcePath)
{
	if (FAILED(CoInitialize(NULL)))
		return FALSE;

	TCHAR szPath[MAX_PATH + 1];
	tstring strDestDir;

	LPITEMIDLIST pidl;
	LPMALLOC pShell;

	if (!SUCCEEDED(SHGetMalloc(&pShell)))
	{
		::CoUninitialize();
		return FALSE;
	}

	if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL, CSIDL_DESKTOPDIRECTORY, &pidl)))
	{
		pShell->Release();
		::CoUninitialize();
		return FALSE;
	}


	if (!SHGetPathFromIDList(pidl, szPath))
	{
		pShell->Free(pidl);
		::CoUninitialize();
		return FALSE;
	}

	pShell->Free(pidl);
	pShell->Release();

	strDestDir = szPath;
	strDestDir += _T("\\") + strName + _T(".lnk");

	IShellLink* psl;
	if (SUCCEEDED(CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (LPVOID*)&psl)))
	{
		psl->SetPath(strSourcePath.c_str());
		IPersistFile* ppf;
		if (SUCCEEDED(psl->QueryInterface(IID_IPersistFile, (LPVOID*)&ppf)))
		{
			USES_CONVERSION;
			if(SUCCEEDED(ppf->Save(CT2W(strDestDir.c_str()), TRUE)))
			{
				ppf->Release();
				psl->Release();
				::CoUninitialize();
				return TRUE;
			}
			else
			{
				ppf->Release();
				psl->Release();
				::CoUninitialize();
				return FALSE;
			}
		}
		else
		{
			ppf->Release();
			psl->Release();
			::CoUninitialize();
			return FALSE;
		}
	}
	else
	{
		::CoUninitialize();
		return FALSE;
	}
}
Exemple #30
0
static BOOL CALLBACK DlgProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lP) {
  FILE *fp;
  int i;
  const char *name, *value, **options = mg_get_valid_option_names();

  switch (msg) {
    case WM_CLOSE:
      DestroyWindow(hDlg);
      break;

    case WM_COMMAND:
      switch (LOWORD(wParam)) {
        case ID_SAVE:
          EnableWindow(GetDlgItem(hDlg, ID_SAVE), FALSE);
          if ((fp = fopen(config_file, "w+")) != NULL) {
            save_config(hDlg, fp);
            fclose(fp);
            mg_stop(ctx);
            start_mongoose(__argc, __argv);
          }
          EnableWindow(GetDlgItem(hDlg, ID_SAVE), TRUE);
          break;
        case ID_RESET_DEFAULTS:
          for (i = 0; options[i] != NULL; i += 3) {
            name = options[i + 1];
            value = options[i + 2] == NULL ? "" : options[i + 2];
            if (is_boolean_option(name)) {
              CheckDlgButton(hDlg, ID_CONTROLS + i / 3, !strcmp(value, "yes") ?
                             BST_CHECKED : BST_UNCHECKED);
            } else {
              SetWindowText(GetDlgItem(hDlg, ID_CONTROLS + i / 3), value);
            }
          }
          break;
      }

      for (i = 0; options[i] != NULL; i += 3) {
        name = options[i + 1];
        if ((is_filename_option(name) || is_directory_option(name)) &&
            LOWORD(wParam) == ID_CONTROLS + i / 3 + ID_FILE_BUTTONS_DELTA) {
          OPENFILENAME of;
          BROWSEINFO bi;
          char path[PATH_MAX] = "";

          memset(&of, 0, sizeof(of));
          of.lStructSize = sizeof(of);
          of.hwndOwner = (HWND) hDlg;
          of.lpstrFile = path;
          of.nMaxFile = sizeof(path);
          of.lpstrInitialDir = mg_get_option(ctx, "document_root");
          of.Flags = OFN_CREATEPROMPT | OFN_NOCHANGEDIR;

          memset(&bi, 0, sizeof(bi));
          bi.hwndOwner = (HWND) hDlg;
          bi.lpszTitle = "Choose WWW root directory:";
          bi.ulFlags = BIF_RETURNONLYFSDIRS;

          if (is_directory_option(name)) {
            SHGetPathFromIDList(SHBrowseForFolder(&bi), path);
          } else {
            GetOpenFileName(&of);
          }

          if (path[0] != '\0') {
            SetWindowText(GetDlgItem(hDlg, ID_CONTROLS + i / 3), path);
          }
        }
      }

      break;

    case WM_INITDIALOG:
      SendMessage(hDlg, WM_SETICON,(WPARAM) ICON_SMALL, (LPARAM) hIcon);
      SendMessage(hDlg, WM_SETICON,(WPARAM) ICON_BIG, (LPARAM) hIcon);
      SetWindowText(hDlg, "Mongoose settings");
      SetFocus(GetDlgItem(hDlg, ID_SAVE));
      for (i = 0; options[i] != NULL; i += 3) {
        name = options[i + 1];
        value = mg_get_option(ctx, name);
        if (is_boolean_option(name)) {
          CheckDlgButton(hDlg, ID_CONTROLS + i / 3, !strcmp(value, "yes") ?
                         BST_CHECKED : BST_UNCHECKED);
        } else {
          SetDlgItemText(hDlg, ID_CONTROLS + i / 3, value == NULL ? "" : value);
        }
      }
      break;
    default:
      break;
  }

  return FALSE;
}