MFC Quick Start Guide (Part 7): File Browser
- Add an edit box to your dialog
- Rename its ID to "IDC_PATHNAME"
- Add an button next to the edit box
- Change the caption to "Edit"
(Fig. 7.4: Edit Button Caption) - Double click the button, this function should be generated in MFC101Dlg.cpp
(Fig. 7.5: Function "OnBnClickedEdit()") - Add the following code:
char caInput[256]; ((CEdit*)GetDlgItem(IDC_PATHNAME))->GetWindowText(LPTSTR(caInput), 256); ShellExecute(NULL, _T("open"), _T("C:\\WINDOWS\\system32\\notepad.exe"), _T(caInput), _T(""), SW_SHOWNORMAL);
(Fig. 7.6: Code) - Let's try it out for a bit, compile the program and build it.
- I had created a text file called "mail.txt" in my C drive
- So I entered "C:\mail.txt" inside the edit box
(Fig. 7.7: Text File Path) - Then click the the "Edit" button
- Here's the result
(Fig. 7.8: Result) - Create another button and rename the caption of which to "Load"
(Fig. 7.9: Load Button) - Change the ID of the button to "IDC_LOAD"
(Fig. 7.10: Load Button ID) - Double click the button and this function should be generated in MDC101Dlg.cpp
(Fig. 7.11; Function "OnBnClickedLoad()") - Add the following segment of code:
TCHAR szFilters[] = _T("Text Document (*.txt)|*.txt|All Files (*.*)|*.*||"); // Create an Open dialog; the default file name extension is ".my". (it's also changed to ".txt") CFileDialog fileDlg(TRUE, _T("txt"), _T("*.txt"), OFN_FILEMUSTEXIST | OFN_HIDEREADONLY, szFilters); // Display the file dialog. When user clicks OK, fileDlg.DoModal() // returns IDOK. if (fileDlg.DoModal() == IDOK) { std::string sPathName = fileDlg.GetPathName(); // Implement opening and reading file in here. //Change the window's title to the opened file's title. std::string sFileName = fileDlg.GetFileTitle(); //SetWindowText(sFileName.c_str()); ((CEdit*)GetDlgItem(IDC_PATHNAME))->SetWindowText(sPathName.c_str()); }
(Fig. 7.12; Code) - Let's try it our again.
- Compile the program and run it
- Click the "Load" button and the file browser should appear
(Fig. 7.13; File Browser) - I chose the ReadMe.txt in Fig. 7.13 and the path of the file was shown in the edit box
(Fig. 7.14: Path) - Click the "Edit" button, the text file should be opened
(Fig. 7.15: Result)
For your reference, here is the code of MFC101Dlg.h and MFC101Dlg.cpp
MFC101Dlg.h
// MFC101Dlg.h : header file // #pragma once #include "afxcmn.h" // CMFC101Dlg dialog class CMFC101Dlg : public CDialogEx { // Construction public: CMFC101Dlg(CWnd* pParent = NULL); // standard constructor // Dialog Data enum { IDD = IDD_MFC101_DIALOG }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support // Implementation protected: HICON m_hIcon; CToolTipCtrl m_ToolTip; // Generated message map functions virtual BOOL OnInitDialog(); afx_msg void OnPaint(); afx_msg HCURSOR OnQueryDragIcon(); DECLARE_MESSAGE_MAP() private: int m_nNumberCount; CString m_sNumberCount; int m_nRedVal; int m_nGreenVal; int m_nBlueVal; public: afx_msg void OnBnClickedButton1(); afx_msg void OnBnClickedButton2(); afx_msg void OnBnClickedButton3(); afx_msg void OnEnChangeRedEdit(); afx_msg void OnEnChangeGreenEdit(); afx_msg void OnEnChangeBlueEdit(); afx_msg void OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar); afx_msg HBRUSH OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor); virtual BOOL PreTranslateMessage(MSG* pMsg); private: CString m_RedSliderEcho; CString m_GreenSliderEcho; CString m_BlueSliderEcho; CSliderCtrl m_RedSliderCtrl; CSliderCtrl m_GreenSliderCtrl; CSliderCtrl m_BlueSliderCtrl; CBrush m_TextBoxBrush; public: afx_msg void OnBnClickedEdit(); afx_msg void OnBnClickedLoad(); };
MFC101Dlg.cpp
// MFC101Dlg.cpp : implementation file // #include "stdafx.h" #include "MFC101.h" #include "MFC101Dlg.h" #include "afxdialogex.h" #include <string> #ifdef _DEBUG #define new DEBUG_NEW #endif // CMFC101Dlg dialog CMFC101Dlg::CMFC101Dlg(CWnd* pParent /*=NULL*/) : CDialogEx(CMFC101Dlg::IDD, pParent) , m_sNumberCount(_T("")) , m_RedSliderEcho(_T("")) , m_GreenSliderEcho(_T("")) , m_BlueSliderEcho(_T("")) , m_nRedVal(0) , m_nGreenVal(0) , m_nBlueVal(0) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CMFC101Dlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Text(pDX, IDC_TEXT_AREA, m_sNumberCount); DDX_Text(pDX, IDC_RED_EDIT, m_RedSliderEcho); DDX_Text(pDX, IDC_GREEN_EDIT, m_GreenSliderEcho); DDX_Text(pDX, IDC_BLUE_EDIT, m_BlueSliderEcho); DDX_Control(pDX, IDC_RED_SLIDER, m_RedSliderCtrl); DDX_Control(pDX, IDC_GREEN_SLIDER, m_GreenSliderCtrl); DDX_Control(pDX, IDC_BLUE_SLIDER, m_BlueSliderCtrl); } BEGIN_MESSAGE_MAP(CMFC101Dlg, CDialogEx) ON_WM_HSCROLL() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_BN_CLICKED(IDC_BUTTON1, &CMFC101Dlg::OnBnClickedButton1) ON_BN_CLICKED(IDC_BUTTON2, &CMFC101Dlg::OnBnClickedButton2) ON_BN_CLICKED(IDC_BUTTON3, &CMFC101Dlg::OnBnClickedButton3) ON_EN_CHANGE(IDC_RED_EDIT, &CMFC101Dlg::OnEnChangeRedEdit) ON_EN_CHANGE(IDC_GREEN_EDIT, &CMFC101Dlg::OnEnChangeGreenEdit) ON_EN_CHANGE(IDC_BLUE_EDIT, &CMFC101Dlg::OnEnChangeBlueEdit) ON_WM_CTLCOLOR() ON_BN_CLICKED(IDC_EDIT, &CMFC101Dlg::OnBnClickedEdit) ON_BN_CLICKED(IDC_LOAD, &CMFC101Dlg::OnBnClickedLoad) END_MESSAGE_MAP() // CMFC101Dlg message handlers BOOL CMFC101Dlg::OnInitDialog() { CDialogEx::OnInitDialog(); // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here m_nNumberCount = 0; //m_nRedVal = 0; //m_nGreenVal = 0; //m_nBlueVal = 0; CSpinButtonCtrl* pSpinColorCtrl = (CSpinButtonCtrl*)GetDlgItem(IDC_RED_SPIN); pSpinColorCtrl->SetRange(0, 255); pSpinColorCtrl->SetBuddy((CEdit *)GetDlgItem(IDC_RED_EDIT)); pSpinColorCtrl->SetPos(m_nRedVal); UDACCEL AccellValue; AccellValue.nInc = 1; // Set how many the value would increase/decrease when a button is clicked pSpinColorCtrl->SetAccel(1, &AccellValue); pSpinColorCtrl = (CSpinButtonCtrl*)GetDlgItem(IDC_GREEN_SPIN); pSpinColorCtrl->SetRange(0, 255); pSpinColorCtrl->SetBuddy((CEdit *)GetDlgItem(IDC_GREEN_EDIT)); pSpinColorCtrl->SetPos(m_nGreenVal); AccellValue.nInc = 1; pSpinColorCtrl->SetAccel(1, &AccellValue); pSpinColorCtrl = (CSpinButtonCtrl*)GetDlgItem(IDC_BLUE_SPIN); pSpinColorCtrl->SetRange(0, 255); pSpinColorCtrl->SetBuddy((CEdit *)GetDlgItem(IDC_BLUE_EDIT)); pSpinColorCtrl->SetPos(m_nBlueVal); AccellValue.nInc = 1; pSpinColorCtrl->SetAccel(1, &AccellValue); m_RedSliderCtrl.SetRange(0, 255, TRUE); m_RedSliderCtrl.SetPos(0); m_RedSliderEcho.Format(_T("%d"), 0); m_GreenSliderCtrl.SetRange(0, 255, TRUE); m_GreenSliderCtrl.SetPos(0); m_GreenSliderEcho.Format(_T("%d"), 0); m_BlueSliderCtrl.SetRange(0, 255, TRUE); m_BlueSliderCtrl.SetPos(0); m_BlueSliderEcho.Format(_T("%d"), 0); m_TextBoxBrush.CreateSolidBrush(RGB(m_nRedVal, m_nGreenVal, m_nBlueVal)); if (!m_ToolTip.Create(this)) { TRACE0("Unable to create the ToolTip!"); } else { m_ToolTip.AddTool((CButton *) GetDlgItem (IDC_BUTTON1), _T("Adjust the three bars to control the text background color.")); m_ToolTip.Activate(TRUE); } return TRUE; // return TRUE unless you set the focus to a control } // If you add a minimize button to your dialog, you will need the code below // to draw the icon. For MFC applications using the document/view model, // this is automatically done for you by the framework. void CMFC101Dlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // device context for painting SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // Center icon in client rectangle int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // Draw the icon dc.DrawIcon(x, y, m_hIcon); } else { CDialogEx::OnPaint(); } } // The system calls this function to obtain the cursor to display while the user drags // the minimized window. HCURSOR CMFC101Dlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } void CMFC101Dlg::OnBnClickedButton1() { // TODO: Add your control notification handler code here m_nNumberCount++; m_sNumberCount.Format(_T("%d"), m_nNumberCount); UpdateData(FALSE); } void CMFC101Dlg::OnBnClickedButton2() { // TODO: Add your control notification handler code here m_nNumberCount = m_nNumberCount + 2; m_sNumberCount.Format(_T("%d"), m_nNumberCount); UpdateData(FALSE); } void CMFC101Dlg::OnBnClickedButton3() { // TODO: Add your control notification handler code here m_nNumberCount = m_nNumberCount + 3; m_sNumberCount.Format(_T("%d"), m_nNumberCount); UpdateData(FALSE); } void CMFC101Dlg::OnEnChangeRedEdit() { // TODO: If this is a RICHEDIT control, the control will not // send this notification unless you override the CDialogEx::OnInitDialog() // function and call CRichEditCtrl().SetEventMask() // with the ENM_CHANGE flag ORed into the mask. // TODO: Add your control notification handler code here char acStr[5] = ""; CEdit* pRedBox = (CEdit *)GetDlgItem(IDC_RED_EDIT); pRedBox->GetWindowText(LPTSTR(acStr), 256); if (!(atoi((const char *)acStr))) pRedBox->SetWindowText(_T("")); else { if ((atoi((const char *)acStr)) > 255) { pRedBox->SetWindowText(_T("255")); } else if ((atoi((const char *)acStr)) < 0) { pRedBox->SetWindowText(_T("0")); } m_nRedVal = atoi((const char *)acStr); } m_RedSliderCtrl.SetPos(m_nRedVal); Invalidate(); } void CMFC101Dlg::OnEnChangeGreenEdit() { // TODO: If this is a RICHEDIT control, the control will not // send this notification unless you override the CDialogEx::OnInitDialog() // function and call CRichEditCtrl().SetEventMask() // with the ENM_CHANGE flag ORed into the mask. // TODO: Add your control notification handler code here char acStr[5] = ""; CEdit* pGreenBox = (CEdit *)GetDlgItem(IDC_GREEN_EDIT); pGreenBox->GetWindowText(LPTSTR(acStr), 256); if (!(atoi((const char *)acStr))) pGreenBox->SetWindowText(_T("")); else { if ((atoi((const char *)acStr)) > 255) { pGreenBox->SetWindowText(_T("255")); } else if ((atoi((const char *)acStr)) < 0) { pGreenBox->SetWindowText(_T("0")); } m_nGreenVal = atoi((const char *)acStr); } m_GreenSliderCtrl.SetPos(m_nGreenVal); Invalidate(); } void CMFC101Dlg::OnEnChangeBlueEdit() { // TODO: If this is a RICHEDIT control, the control will not // send this notification unless you override the CDialogEx::OnInitDialog() // function and call CRichEditCtrl().SetEventMask() // with the ENM_CHANGE flag ORed into the mask. // TODO: Add your control notification handler code here char acStr[5] = ""; CEdit* pBlueBox = (CEdit *)GetDlgItem(IDC_BLUE_EDIT); pBlueBox->GetWindowText(LPTSTR(acStr), 256); if (!(atoi((const char *)acStr))) pBlueBox->SetWindowText(_T("")); else { if ((atoi((const char *)acStr)) > 255) { pBlueBox->SetWindowText(_T("255")); } else if ((atoi((const char *)acStr)) < 0) { pBlueBox->SetWindowText(_T("0")); } m_nBlueVal = atoi((const char *)acStr); } m_BlueSliderCtrl.SetPos(m_nBlueVal); Invalidate(); } void CMFC101Dlg::OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar) { // TODO: Add your message handler code here and/or call default if ((pScrollBar == (CScrollBar *)&m_RedSliderCtrl) || (pScrollBar == (CScrollBar *)&m_GreenSliderCtrl) || (pScrollBar == (CScrollBar *)&m_BlueSliderCtrl)) { int nIndex; nIndex = m_RedSliderCtrl.GetPos(); m_RedSliderEcho.Format(_T("%d"), nIndex); m_nRedVal = nIndex; nIndex = m_GreenSliderCtrl.GetPos(); m_GreenSliderEcho.Format(_T("%d"), nIndex); m_nGreenVal = nIndex; nIndex = m_BlueSliderCtrl.GetPos(); m_BlueSliderEcho.Format(_T("%d"), nIndex); m_nBlueVal = nIndex; UpdateData(FALSE); } else { CDialog::OnHScroll(nSBCode, nPos, pScrollBar); } Invalidate(); } HBRUSH CMFC101Dlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor) { HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor); //// TODO: Change any attributes of the DC here //// TODO: Return a different brush if the default is not desired //return hbr; if (pWnd->GetDlgCtrlID() == IDC_TEXT_AREA) { pDC->SetTextColor(RGB(107, 78, 255)); pDC->SetBkColor(RGB(m_nRedVal, m_nGreenVal, m_nBlueVal)); hbr = m_TextBoxBrush; } return hbr; } BOOL CMFC101Dlg::PreTranslateMessage(MSG* pMsg) { m_ToolTip.RelayEvent(pMsg); return CDialog::PreTranslateMessage(pMsg); } void CMFC101Dlg::OnBnClickedEdit() { // TODO: Add your control notification handler code here char caInput[256]; ((CEdit*)GetDlgItem(IDC_PATHNAME))->GetWindowText(LPTSTR(caInput), 256); ShellExecute(NULL, _T("open"), _T("C:\\WINDOWS\\system32\\notepad.exe"), _T(caInput), _T(""), SW_SHOWNORMAL); } void CMFC101Dlg::OnBnClickedLoad() { // TODO: Add your control notification handler code here // szFilters is a text string that includes two file name filters: // "*.my" for "MyType Files" (here they are changed to "*.txt")and "*.*' for "All Files." TCHAR szFilters[] = _T("Text Document (*.txt)|*.txt|All Files (*.*)|*.*||"); // Create an Open dialog; the default file name extension is ".my". (it's also changed to ".txt") CFileDialog fileDlg(TRUE, _T("txt"), _T("*.txt"), OFN_FILEMUSTEXIST | OFN_HIDEREADONLY, szFilters); // Display the file dialog. When user clicks OK, fileDlg.DoModal() // returns IDOK. if (fileDlg.DoModal() == IDOK) { std::string sPathName = fileDlg.GetPathName(); // Implement opening and reading file in here. //Change the window's title to the opened file's title. std::string sFileName = fileDlg.GetFileTitle(); //SetWindowText(sFileName.c_str()); ((CEdit*)GetDlgItem(IDC_PATHNAME))->SetWindowText(sPathName.c_str()); } }
MFC Quick Start Guide (Part 7): File Browser
Reviewed by Kevin Lai
on
10:33:00 AM
Rating:
No comments: