文件打開(保存)對話框:GetOpenFileName和 GetSaveFileName

void Test() 
{
	TCHAR strFilter[]		= _T("Bitmap Files(*.bmp)\0*.bmp\0")
						_T("JPEG Files(*.jpeg;*jpg)\0*.jpeg;*.jpg\0")
						_T("PNG Files(*.png)\0*.png\0")
						_T("All Files(*.*)\0*.*\0");


	TCHAR strFile[MAX_PATH]	= _T("未命名");
	TCHAR strFileTitle[256]	= {0};
	TCHAR strInitiaDir[]		= _T("D:\\DeskTop");
	TCHAR strTitle[]			= _T("請選擇");


	OPENFILENAME ofn;         
	ZeroMemory(&ofn, sizeof(ofn));


	// 指定結構的大小,以字節爲單位
	ofn.lStructSize			= sizeof(ofn);


	/*Handle to the window that owns the dialog box. 
	This member can be any valid window handle, or it can be NULL if the dialog box has no owner.*/
	ofn.hwndOwner           = m_hWnd;	


	// Not supported.
	//ofn.hInstance;		


	// 過濾器字符串的長指針,需以兩個空字符結尾
	ofn.lpstrFilter 		= strFilter;			


	// Not supported.
	//ofn.lpstrCustomFilter;	


	// Not supported.
	//ofn.nMaxCustFilter;	


	// 過濾器序號(由1開始,如果該值爲0表示第一個)			
	ofn.nFilterIndex		= 3;			


	/*指向包含初始化文件名編輯控件使用的文件名的緩衝。如果不需要初始值,這個緩衝的第一個字符必須是NULL。
	當GetOpenFileName或GetSaveFileName函數返回成功時,這個緩衝包含驅動器,路徑,文件名,及所選擇的文件的擴展名。 
	If the buffer is too small, the function returns FALSE. In this case, 
	the first two bytes of the lpstrFile buffer contain the required size, in bytes or characters.*/
	ofn.lpstrFile			= strFile;		


	/*Specifies the size, in bytes (ANSI version) or 16-bit characters (Unicode version), of the buffer pointed to by lpstrFile. 
	The GetOpenFileName and GetSaveFileName functions return FALSE if the buffer is too small to contain the file information. 
	The buffer should be at least 256 characters long.*/
	ofn.nMaxFile			= sizeof(strFile);	


	// 指向接收選擇的文件的文件名和擴展名的緩衝(不帶路徑信息)。這個成員可以是NULL。
	ofn.lpstrFileTitle		= strFileTitle;			


	/*指定lpstrFileTitle緩衝的大小,以TCHARs爲單位。對於ANSI版本,是字節的個數;
	對於Unicode版本,是字節的個數。如果lpstrFileTitle是NULL,這個成員被忽略。*/
	ofn.nMaxFileTitle		= sizeof(strFileTitle);	


	// 打開對話框的初始目錄,可以爲NULL
	ofn.lpstrInitialDir		= strInitiaDir;	


	// 打開對話框標題欄的提示文字
	ofn.lpstrTitle			= strTitle;		


	/*A bitmask of flags used to initialize the dialog box. When the dialog box returns, 
	it sets these flags to indicate the user's input. This member can be a combination of the following flags.*/
	ofn.Flags				= 0;	


	// 指定從路徑開始到通過lpstrFile指定的文件名字符串基於0的偏移
	ofn.nFileOffset			= 0;	


	// 指定從路徑開始到通過lpstrFile指定的文件名字符串中擴展名基於0的偏移
	ofn.nFileExtension		= 0;					


	/*指向包含默認擴展名的緩衝。如果用戶忘記輸入擴展名,GetOpenFileName和GetSaveFileName附加這個擴展名到文件名中。
	這個字符串可以是任一長度,但但只有頭三個字符被附加。字符串不應該包含一個句點(.)。
	如果這個成員是NULL並且用戶忘記了輸入一個擴展名,那麼將沒有擴展名被附加。*/
	ofn.lpstrDefExt			= _T("bmp");				
	
	//ofn.lCustData;								// Not supported.
	//ofn.lpfnHook;									// Not supported.
	//ofn.lpTemplateName;							// Not supported.




	CString str;
	if (GetOpenFileName(&ofn))
	{
		str = ofn.lpstrFile;
		AfxMessageBox(str);
	}


	if (GetSaveFileName(&ofn))
	{
		str = ofn.lpstrFile;
		AfxMessageBox(str);
	}
}





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章