MFC CString: double not displaying - c++

I have two variables, m_GridSize and m_TimeDisplay, which update themselves according to a variable called "world" here. Now, the MFC program will display the words "Grid size: " and "Time: ", but it will not display the actual values of the doubles. I am using Visual Studio Community 2013 to make a Win32 GUI application.
I am having trouble with the CString Format function.
EDIT to include full code:
// smart_parking_guiDlg.cpp : implementation file
//
#include "stdafx.h"
#include "smart_parking_gui.h"
#include "smart_parking_guiDlg.h"
#include "afxdialogex.h"
#include "Cadd_Destination.h"
#include "Cadd_Lot.h"
#include "Cadd_Driver.h"
#include "Commands.h" // Used to handle commands
#include "Grid.h" // Contains the grid
#include <string>
#include <io.h>
#include <fcntl.h>
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// Csmart_parking_guiDlg dialog
Csmart_parking_guiDlg::Csmart_parking_guiDlg(CWnd* pParent /*=NULL*/)
: CDialogEx(Csmart_parking_guiDlg::IDD, pParent)
, m_EchoSize(_T("Grid size: "))
, m_EchoTime(_T("Time: "))
, m_EchoStatus(_T("Open"))
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
this->world = new Grid(10, 5); // default grid
}
void Csmart_parking_guiDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
DDX_Text(pDX, IDC_ST_GRIDSIZE, m_EchoSize);
DDX_Text(pDX, IDC_ST_TIME, m_EchoTime);
DDX_Text(pDX, IDC_ST_STATUS, m_EchoStatus);
}
BEGIN_MESSAGE_MAP(Csmart_parking_guiDlg, CDialogEx)
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDC_B_OPEN_CONFIG, &Csmart_parking_guiDlg::OnBnClickedBOpenConfig)
ON_BN_CLICKED(IDC_B_SAVECONFIG, &Csmart_parking_guiDlg::OnBnClickedBSaveconfig)
ON_BN_CLICKED(IDC_B_NEXTEVENT, &Csmart_parking_guiDlg::OnBnClickedBNextevent)
ON_BN_CLICKED(IDC_B_NEWDEST, &Csmart_parking_guiDlg::OnBnClickedBNewdest)
ON_BN_CLICKED(IDC_B_NEWLOT, &Csmart_parking_guiDlg::OnBnClickedBNewlot)
ON_BN_CLICKED(IDC_B_NEWDRIVER, &Csmart_parking_guiDlg::OnBnClickedBNewdriver)
ON_BN_CLICKED(IDC_B_SIMEND, &Csmart_parking_guiDlg::OnBnClickedBSimend)
ON_BN_CLICKED(IDC_B_SHOWSTATUS, &Csmart_parking_guiDlg::OnBnClickedBShowstatus)
END_MESSAGE_MAP()
// Csmart_parking_guiDlg message handlers
BOOL Csmart_parking_guiDlg::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
return TRUE;
}
// 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 Csmart_parking_guiDlg::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 Csmart_parking_guiDlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
void Csmart_parking_guiDlg::OnBnClickedBOpenConfig()
{
wchar_t szFilters[] = _T("Text Files (*.txt)|*.txt|All Files (*.*)|*.*||");
// Create an Open dialog
CFileDialog fileDlg(TRUE, _T("txt"), _T("*.txt"),
OFN_FILEMUSTEXIST | OFN_HIDEREADONLY, szFilters, this); // Display the file dialog.
// When user clicks OK, fileDlg.DoModal() returns IDOK.
if (fileDlg.DoModal() == IDOK)
{
CString m_strPathname = fileDlg.GetPathName();
CT2CA converter(m_strPathname);
std::string fileToOpen(converter);
// TODO: Open Grid file
open_file(*world, fileToOpen);
//Change the window's title to the opened file's title.
CString fileName = fileDlg.GetFileTitle();
SetWindowText(fileName);
}
}
void Csmart_parking_guiDlg::OnBnClickedBSaveconfig()
{
// TODO: Add your control notification handler code here
// szFilters is a text string that includes two file name filters:
// "*.my" for "MyType Files" and "*.*' for "All Files."
TCHAR szFilters[] = _T("Text Files (*.txt)|*.txt|All Files (*.*)|*.*||");
// Create a Save dialog
CFileDialog fileDlg(FALSE, _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)
{
CString pathName = fileDlg.GetPathName();
CT2CA converter(pathName);
std::string fileToWrite(converter);
// Implement opening and reading file in here.
write_file(*world, fileToWrite);
//Change the window's title to the opened file's title.
CString fileName = fileDlg.GetFileTitle();
SetWindowText(fileName);
}
}
void Csmart_parking_guiDlg::OnBnClickedBNextevent()
{
// TODO: Add your control notification handler code here
run_simulation(*world);
m_GridSize = world->getGridSize(); // double
m_TimeDisplay = world->getTime(); // double
// THIS DOESN'T WORK
m_EchoSize.Format(_T("Grid size: %g"), m_GridSize);
m_EchoTime.Format(_T("Time: %g"), m_TimeDisplay);
UpdateData(FALSE);
GetDlgItem(IDC_ST_GRIDSIZE)->InvalidateRect(NULL);
GetDlgItem(IDC_ST_TIME)->InvalidateRect(NULL);
}
void Csmart_parking_guiDlg::OnBnClickedBSimend() // On clicking, simulation jumps to the very end.
{
jump_to_end(*world);
m_GridSize = world->getGridSize();
m_TimeDisplay = world->getTime();
// THIS DOESN'T WORK
m_EchoSize.Format(_T("Grid size: %g"), m_GridSize);
m_EchoTime.Format(_T("Time: %g"), m_TimeDisplay);
UpdateData(FALSE);
GetDlgItem(IDC_ST_GRIDSIZE)->InvalidateRect(NULL);
GetDlgItem(IDC_ST_TIME)->InvalidateRect(NULL);
}
void Csmart_parking_guiDlg::OnBnClickedBNewdest()
{
// TODO: Add your control notification handler code here
Cadd_Destination Dlg;
Dlg.DoModal();
}
void Csmart_parking_guiDlg::OnBnClickedBNewlot()
{
// TODO: Add your control notification handler code here
Cadd_Lot Dlg;
Dlg.DoModal();
}
void Csmart_parking_guiDlg::OnBnClickedBNewdriver() // Opens a dialog to input a new driver. Only works with added destination.
{
if (world->getDestinationCount() != 0) {
Cadd_Driver Dlg;
Dlg.DoModal();
}
}
void Csmart_parking_guiDlg::OnBnClickedBShowstatus()
{
// TODO: Add your control notification handler code here
}
Is there any way to fix this in order to make the values of the doubles show up in the GUI? I have tried the answer shown here
C++ MFC double to CString
but the numbers do not show up at all. There are no syntax errors. The code works if I use %d and replace the values with integers, but it doesn't work with double values, which is what I used in my initial classes.

I have fixed the problem myself.
As it turns out, the issue had more to do with my GUI. It turns out that the Static Text has a set length set in the Visual Studio Dialog Editor (accessed through the Resource View) and the length was too short to hold both the string containing "Grid size:" and the actual numbers. (The first Static Text initially could only hold one digit for both of them) I fixed it by extending the width of the Static Text in my GUI, and that fixed the problem.

As implied by the name, Static text controls are not expected to change once they are created. They don't automatically repaint when you change their content with SetWindowText, which is what DDX_Text calls to set the new text. You need to inform Windows that the contents have changed and the control needs repainting:
GetDlgItem(IDC_ST_GRIDSIZE)->InvalidateRect(NULL);

Related

This program thows exception. Want to create program to display directory structure with tree control in mfc

**FileEnumTreeControl.cpp file**
// FileEnumTreeControl.cpp : Defines the class behaviors for the
application.
//
#include "stdafx.h"
#include "FileEnumTreeControl.h"
#include "FileEnumTreeControlDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CFileEnumTreeControlApp
BEGIN_MESSAGE_MAP(CFileEnumTreeControlApp, CWinApp)
ON_COMMAND(ID_HELP, &CWinApp::OnHelp)
END_MESSAGE_MAP()
// CFileEnumTreeControlApp construction
CFileEnumTreeControlApp::CFileEnumTreeControlApp()
{
// TODO: add construction code here,
// Place all significant initialization in InitInstance
}
// The one and only CFileEnumTreeControlApp object
CFileEnumTreeControlApp theApp;
// CFileEnumTreeControlApp initialization
BOOL CFileEnumTreeControlApp::InitInstance()
{
// InitCommonControlsEx() is required on Windows XP if an application
// manifest specifies use of ComCtl32.dll version 6 or later to enable
// visual styles. Otherwise, any window creation will fail.
INITCOMMONCONTROLSEX InitCtrls;
InitCtrls.dwSize = sizeof(InitCtrls);
// Set this to include all the common control classes you want to use
// in your application.
InitCtrls.dwICC = ICC_WIN95_CLASSES;
InitCommonControlsEx(&InitCtrls);
CWinApp::InitInstance();
AfxEnableControlContainer();
// Standard initialization
// If you are not using these features and wish to reduce the size
// of your final executable, you should remove from the following
// the specific initialization routines you do not need
// Change the registry key under which our settings are stored
// TODO: You should modify this string to be something appropriate
// such as the name of your company or organization
SetRegistryKey(_T("Local AppWizard-Generated Applications"));
CFileEnumTreeControlDlg dlg;
m_pMainWnd = &dlg;
INT_PTR nResponse = dlg.DoModal();
if (nResponse == IDOK)
{
// TODO: Place code here to handle when the dialog is
// dismissed with OK
}
else if (nResponse == IDCANCEL)
{
// TODO: Place code here to handle when the dialog is
// dismissed with Cancel
}
// Since the dialog has been closed, return FALSE so that we exit the
// application, rather than start the application's message pump.
return FALSE;
}
**FileEnumTreeControlDlg.cpp file**
// FileEnumTreeControlDlg.cpp : implementation file
//
#include "stdafx.h"
#include <string>
#include <iostream>
#include "FileEnumTreeControl.h"
#include "FileEnumTreeControlDlg.h"
#include<windows.h>
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CFileEnumTreeControlDlg dialog
CFileEnumTreeControlDlg::CFileEnumTreeControlDlg(CWnd* pParent /*=NULL*/)
: CDialog(CFileEnumTreeControlDlg::IDD, pParent)
, m_strTree(_T(""))
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CFileEnumTreeControlDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Text(pDX, IDC_STATIC_TXT, m_strTree);
DDX_Control(pDX, IDC_TREE1, m_treeCtrl);
}
BEGIN_MESSAGE_MAP(CFileEnumTreeControlDlg, CDialog)
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
// CFileEnumTreeControlDlg message handlers
BOOL CFileEnumTreeControlDlg::OnInitDialog()
{
CDialog::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
WIN32_FIND_DATA data;
HTREEITEM hItem, hCar;
HANDLE find=FindFirstFile(L"D:\\*",&data);
hItem = m_treeCtrl.InsertItem(L"D", TVI_ROOT);
if(find!=INVALID_HANDLE_VALUE)
{
do
{
hCar = m_treeCtrl.InsertItem(data.cFileName, hItem);
if (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
WIN32_FIND_DATA data2;
wchar_t* dir=L"D:\\";
wcsncat(dir,data.cFileName,wcslen(data.cFileName)-4);
wcsncat(dir,L"\\*",3);
HANDLE find2=FindFirstFile(dir,&data2);
if(find2!=INVALID_HANDLE_VALUE)
{
do{
m_treeCtrl.InsertItem(data2.cFileName,hCar);
}while(FindNextFile(find2,&data2));
}
}
}while(FindNextFile(find,&data));
FindClose(find);
}
// TODO: Add extra initialization here
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 CFileEnumTreeControlDlg::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
{
CDialog::OnPaint();
}
}
// The system calls this function to obtain the cursor to display while the
user drags
// the minimized window.
HCURSOR CFileEnumTreeControlDlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
**FileEnumTreeControl.h : main header file for the PROJECT_NAME
application**
//
#pragma once
#ifndef __AFXWIN_H__
#error "include 'stdafx.h' before including this file for PCH"
#endif
#include "resource.h" // main symbols
// CFileEnumTreeControlApp:
// See FileEnumTreeControl.cpp for the implementation of this class
//
class CFileEnumTreeControlApp : public CWinApp
{
public:
CFileEnumTreeControlApp();
// Overrides
public:
virtual BOOL InitInstance();
// Implementation
DECLARE_MESSAGE_MAP()
};
extern CFileEnumTreeControlApp theApp;
FileEnumTreeControlDlg.h : header file
//
#pragma once
#include "afxcmn.h"
// CFileEnumTreeControlDlg dialog
class CFileEnumTreeControlDlg : public CDialog
{
// Construction
public:
CFileEnumTreeControlDlg(CWnd* pParent = NULL); // standard constructor
// Dialog Data
enum { IDD = IDD_FILEENUMTREECONTROL_DIALOG };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
// Implementation
protected:
HICON m_hIcon;
// Generated message map functions
virtual BOOL OnInitDialog();
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
DECLARE_MESSAGE_MAP()
public:
CString m_strTree;
CTreeCtrl m_treeCtrl;
};
FileEnumTreeControl.h : main header file for the PROJECT_NAME application
#pragma once
#ifndef __AFXWIN_H__
#error "include 'stdafx.h' before including this file for PCH"
#endif
#include "resource.h" // main symbols
// CFileEnumTreeControlApp:
// See FileEnumTreeControl.cpp for the implementation of this class
//
class CFileEnumTreeControlApp : public CWinApp
{
public:
CFileEnumTreeControlApp();
// Overrides
public:
virtual BOOL InitInstance();
// Implementation
DECLARE_MESSAGE_MAP()
};
extern CFileEnumTreeControlApp theApp;
This program is created in mfc and everything working just fine but i am not able to expand inner directories as unable to give complete path to FindFirstFile() please tell me how to pass dynamic path to FindFirstFile()
Let me guess, its going wrong in this line:
wchar_t* dir=L"D:\\";
wcsncat(dir,data.cFileName,wcslen(data.cFileName)-4);
That's because you have defined dir to be wchar* that points to a static block of memory that contains "D:\" and doesn't have enough free space after to have the rest of the string concatenated into it.
The easiest way to fix it it to replace the definition of dir to be a stack-allocated array such as
wchar_t dir[MAX_PATH]
that allocates a long block of empty space that you can then copy the directory name into. It'll also have the advantage that it will be automatically deallocated when the program exits the code block. You should also be using the 3rd parameter to wcsncat to be the size of the buffer, not the size of the string you want copied. Read the function documentation carefully.
If you're new to C/C++, you need to read up on memory allocation, strings and arrays and buffers before going further or you'll make big mistakes.

VC++ Trasforming a sample application into a DLL

I have a project where I received an sample code that is an exe, that basically loads to a dialog two activeX controls.
I need to make an DLL to use the functions of that controls.
What's the best strategy to do this?
I think my DLL need's to make an instance of the window.
and when the window is build get pointers to the activeX controls to make stuff happen.
What is the best strategy to do this? or if it is even possible?
The App Code:
StartUp.h
#pragma once
#ifndef __AFXWIN_H__
#error "include 'stdafx.h' before including this file for PCH"
#endif
#include "resource.h" // main symbols
// CStartUpApp:
// See StartUp.cpp for the implementation of this class
//
class CStartUpApp : public CWinApp
{
public:
CStartUpApp();
// Overrides
public:
virtual BOOL InitInstance();
// Implementation
DECLARE_MESSAGE_MAP()
};
extern CStartUpApp theApp;
StartUpDlg.h
#pragma once
#include "xnssdkdevicectrl.h"
#include "xnssdkwindowctrl.h"
// CStartUpDlg dialog
class CStartUpDlg : public CDialog
{
// Construction
public:
CStartUpDlg(CWnd* pParent = NULL); // standard constructor
// Dialog Data
enum { IDD = IDD_STARTUP_DIALOG };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
// Implementation
protected:
HICON m_hIcon;
// Generated message map functions
virtual BOOL OnInitDialog();
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
DECLARE_MESSAGE_MAP()
private:
// [ XNS ACTIVEX HELP ]
// -----------------------------------------------------------------------
// XNS Device control and Window control variables
// -----------------------------------------------------------------------
CXnssdkwindowctrl m_ctrlXnsWindow; // XnsWindow control
CXnssdkdevicectrl m_ctrlXnsDevice; // XnsDevice control
public:
afx_msg void OnBnClickedOk();
};
StartUp.cpp
#include "stdafx.h"
#include "StartUp.h"
#include "StartUpDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CStartUpApp
BEGIN_MESSAGE_MAP(CStartUpApp, CWinApp)
ON_COMMAND(ID_HELP, &CWinApp::OnHelp)
END_MESSAGE_MAP()
// CStartUpApp construction
CStartUpApp::CStartUpApp()
{
// TODO: add construction code here,
// Place all significant initialization in InitInstance
}
// The one and only CStartUpApp object
CStartUpApp theApp;
// CStartUpApp initialization
BOOL CStartUpApp::InitInstance()
{
// InitCommonControlsEx() is required on Windows XP if an application
// manifest specifies use of ComCtl32.dll version 6 or later to enable
// visual styles. Otherwise, any window creation will fail.
INITCOMMONCONTROLSEX InitCtrls;
InitCtrls.dwSize = sizeof(InitCtrls);
// Set this to include all the common control classes you want to use
// in your application.
InitCtrls.dwICC = ICC_WIN95_CLASSES;
InitCommonControlsEx(&InitCtrls);
CWinApp::InitInstance();
AfxEnableControlContainer();
// Standard initialization
// If you are not using these features and wish to reduce the size
// of your final executable, you should remove from the following
// the specific initialization routines you do not need
// Change the registry key under which our settings are stored
// TODO: You should modify this string to be something appropriate
// such as the name of your company or organization
SetRegistryKey(_T("Local AppWizard-Generated Applications"));
CStartUpDlg dlg;
m_pMainWnd = &dlg;
INT_PTR nResponse = dlg.DoModal();
if (nResponse == IDOK)
{
// TODO: Place code here to handle when the dialog is
// dismissed with OK
}
else if (nResponse == IDCANCEL)
{
// TODO: Place code here to handle when the dialog is
// dismissed with Cancel
}
// Since the dialog has been closed, return FALSE so that we exit the
// application, rather than start the application's message pump.
return FALSE;
}
StartUpDlg.cpp
#include "stdafx.h"
#include "StartUp.h"
#include "StartUpDlg.h"
// [ XNS ACTIVEX HELP ]
// -----------------------------------------------------------------------
// This files are installed in {$SDK path}\sample_code\include
// You should include this files
// -----------------------------------------------------------------------
#include "XnsCommon.h"
#include "XnsDeviceInterface.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// Macro for OutputDebugString()
#define DBG_LOG(...) do{\
CString strMessage = _T("");\
strMessage.AppendFormat(_T("(%S:%d)"), __FUNCTION__, __LINE__); \
strMessage.AppendFormat(__VA_ARGS__);\
OutputDebugString(strMessage);\
}while(0);
// Macro for AfxMessageBox()
#define ERROR_BOX(...) do{\
CString strMessage = _T("");\
strMessage.Format(__VA_ARGS__);\
AfxMessageBox(strMessage);\
}while(0);
// CAboutDlg dialog used for App About
class CAboutDlg : public CDialog
{
public:
CAboutDlg();
// Dialog Data
enum { IDD = IDD_ABOUTBOX };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
// Implementation
protected:
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
END_MESSAGE_MAP()
// CStartUpDlg dialog
CStartUpDlg::CStartUpDlg(CWnd* pParent /*=NULL*/)
: CDialog(CStartUpDlg::IDD, pParent)
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CStartUpDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_XNSSDKDEVICECTRL, m_ctrlXnsDevice);
DDX_Control(pDX, IDC_XNSSDKWINDOWCTRL, m_ctrlXnsWindow);
}
BEGIN_MESSAGE_MAP(CStartUpDlg, CDialog)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
//}}AFX_MSG_MAP
ON_BN_CLICKED(IDOK, &CStartUpDlg::OnBnClickedOk)
END_MESSAGE_MAP()
// CStartUpDlg message handlers
BOOL CStartUpDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// Add "About..." menu item to system menu.
// IDM_ABOUTBOX must be in the system command range.
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
CString strAboutMenu;
strAboutMenu.LoadString(IDS_ABOUTBOX);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// 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
// [ XNS ACTIVEX HELP ]
// -----------------------------------------------------------------------
// Initializes the DLL files.
// For this, XnsActiveX library requires config.xml, device.xml,
// and xns.xml files and the DLL file list should be mentioned
// in Xns.xml file. The path of the DLL file can not exceed 512 bytes
// in length. The XnsActiveX library searches for xns.xml using
// XnsSDKDevice.ocx installed in "{$SDK path}\Config" folder.
// -----------------------------------------------------------------------
long nRet = m_ctrlXnsDevice.Initialize();
if (nRet != ERR_SUCCESS)
{
DBG_LOG(_T("XnsSdkDevice:: Initialize() fail: errno=[%d]\n"), nRet);
}
// [ XNS ACTIVEX HELP ]
// -----------------------------------------------------------------------
// Initializes the XnsSdkWindow control.
// Namely, this will specify the window handle in order to display
// images on the screen.
// -----------------------------------------------------------------------
nRet = m_ctrlXnsWindow.Initialize(NULL, NULL);
DBG_LOG(_T("XnsSdkWindow:: Initialize() return=[%d](%s)\n"),
nRet, m_ctrlXnsDevice.GetErrorString(nRet));
return TRUE; // return TRUE unless you set the focus to a control
}
void CStartUpDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialog::OnSysCommand(nID, lParam);
}
}
// 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 CStartUpDlg::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
{
CDialog::OnPaint();
}
}
// The system calls this function to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR CStartUpDlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
void CStartUpDlg::OnBnClickedOk()
{
// TODO: Add your control notification handler code here
OnOK();
}
my dll header
__declspec(dllexport) long init();//initilize app with activeX controls in window
__declspec(dllexport) long getDlgInstance();//get dlg handle to be able to call activeX
__declspec(dllexport) long connect(long handle);//do stuff
Shouldn't be that hard...
Without having seen your code (how could I?), I assume you defined functions to return the pointers of the activeX controls to the caller.
Judging by the questions you asked earlier you know how to make a DLL. Get all the code you need in a new DLL project, export only the functions you want to access from the host application and you're done
Your DLL code would look something like
__declspec (dllexport) CStartUpDlg *ShowStartUpDlg()
{ AFX_MANAGE_STATE(AfxGetStaticModuleState()); // in case the dialog is in the DLL's .rc file
// alternate to the above line: AfxSetResourceHandle(hInstance); // hInstance is what you get in the DLL's InitInstance()
CStartUpDlg *pDlg = new CStartUpDlg();
if (pDlg == NULL)
return NULL;
if (!pDlg->Create(IDD_STARTUP_DLG))
return NULL;
pDlg->ShowWindow(SW_SHOW);
return pDlg; // make sure you close the dialog and delete pDlg at the end of your program
}

Why does MFC DoModal returns -1 ? What does -1 mean?

I am very new to MFC and have been asked to create a MFC application in Visual Studio 2008. I am trying to Create two dialog. The first one opens on launch and if OK is pressed on the first one, the second dialog opens. However my first dialog opens properly but the second one returns -1 when I call DoModal(). Can anybody please let me know what am I doing wrong ? The -1 according to MSDN documentation is "something has gone wrong". I couldn't figure out what I am doing wrong.
// The main file from where the dialogs are launched - Encrypt.cpp
#include "stdafx.h"
#include "Encrypt.h"
#include "MainDialog.h"
#include "AddlDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
BEGIN_MESSAGE_MAP(CEncryptApp, CWinApp)
ON_COMMAND(ID_HELP, &CWinApp::OnHelp)
END_MESSAGE_MAP()
CEncryptApp::CEncryptApp()
{
}
CEncryptApp theApp;
BOOL CEncryptApp::InitInstance()
{
CWinApp::InitInstance();
AfxEnableControlContainer();
AfxInitRichEdit();
CMainDialog dlg;
INT_PTR nResponse = dlg.DoModal();
if (nResponse == IDOK)
{
CAddlDlg ldg;
INT_PTR nResponse = ldg.DoModal();
switch (nResponse)
{
case -1:
AfxMessageBox(_T("-1"));
break;
case IDABORT:
AfxMessageBox(_T("1!"));
break;
case IDOK:
AfxMessageBox(_T("2!"));
break;
case IDCANCEL:
AfxMessageBox(_T("3!"));
break;
default:
AfxMessageBox(nResponse);
break;
};
}
else if (nResponse == IDCANCEL)
{
}
return FALSE;
}
This is the main dialog
// Main Dialog
#include "stdafx.h"
#include "Encrypt.h"
#include "MainDialog.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
IMPLEMENT_DYNAMIC(CMainDialog, CDialog)
CMainDialog::CMainDialog(CWnd* pParent /*=NULL*/)
: CDialog(CMainDialog::IDD, pParent)
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
CMainDialog::~CMainDialog()
{
}
void CMainDialog::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CMainDialog, CDialog)
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
BOOL CMainDialog::OnInitDialog()
{
CDialog::OnInitDialog();
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
return TRUE; // return TRUE unless you set the focus to a control
}
void CMainDialog::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;
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
}
HCURSOR CMainDialog::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
// The second dialog
#include "stdafx.h"
#include "Encrypt.h"
#include "AddlDlg.h"
IMPLEMENT_DYNAMIC(CAddlDlg, CDialog)
CAddlDlg::CAddlDlg(CWnd* pParent /*=NULL*/)
: CDialog(CAddlDlg::IDD, pParent)
{ // Reaches until here
}
CAddlDlg::~CAddlDlg()
{
}
void CAddlDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
}
BOOL CAddlDlg::OnInitDialog()
{
CDialog::OnInitDialog();
return TRUE;
}
BEGIN_MESSAGE_MAP(CAddlDlg, CDialog)
END_MESSAGE_MAP()
When I try printing debug statements, I enter into the constructor of the second dialog but the OnInitDialog never gets called. Can someone please help me?
**UPDATE :: **
The error I see on further debugging says it is on line 311 in dlgcore.cpp in the function ::CreateDialogIndirect with the actual error is
::CreateDialogIndirect() did NOT create the window (ie. due to error in template) and returns NULL.
I do not what that means. Can some one explain me ?
From MSDN site:
The return value is –1 if the function could not create the dialog box, or IDABORT if some other error occurred, in which case the Output window will contain error information from GetLastError.
Error citation can be found here: http://msdn.microsoft.com/en-us/library/619z63f5.aspx
The system is unable to create and run your dialog. You can read the provided MSDN link for more information.
It is likely you have a control or DLL that is not registered correctly that the dialog needs and therefore cannot find.

Changing Cursor of a button in MFC

I am trying to change cursor of a button in MFC dialog. i have used
BOOL CStartDlg::OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message)
{
if ( m_changeCursor )
{
::SetCursor(AfxGetApp()->LoadStandardCursor(IDC_HAND));
return TRUE;
}
return CDialog::OnSetCursor(pWnd, nHitTest, message);
}
but it is changing cursor for whole dialog box. m_button is object of CButton class.
Please tell me how to change cursor of a button.I have tryed this also but not working
m_button1.SetCursor(::LoadCursor(NULL, IDC_HAND));
Call the LoadCursor() function and pass its returned value to the CMFCButton::SetMouseCursor() member function. Here is an example:
BOOL CExerciseDlg::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_Calculate.SetMouseCursor(LoadCursor(AfxGetInstanceHandle(),
MAKEINTRESOURCE(IDC_CURSOR1)));
return TRUE;
}
refer http://www.functionx.com/visualc/controls/mfcbtn.htm#subtitle
also refer Api CWinApp::LoadCursor

login form creation in mfc

I wrote a code in mfc for login form
my code is here
// login1Dlg.cpp : implementation file
//
#include "stdafx.h"
#include "login1.h"
#include "login1Dlg.h"
#include "afxdialogex.h"
//#include "LOGINDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// Clogin1Dlg dialog
Clogin1Dlg::Clogin1Dlg(CWnd* pParent /*=NULL*/)
: CDialogEx(Clogin1Dlg::IDD, pParent)
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
m_username = _T("");
m_password = _T("");
}
void Clogin1Dlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
DDX_Text(pDX, IDC_USERNAME_EDIT, m_username);
DDX_Text(pDX, IDC_PASSWORD_EDIT, m_password);
}
BEGIN_MESSAGE_MAP(Clogin1Dlg, CDialogEx)
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDC_OK_BUTTON, &Clogin1Dlg::OnBnClickedOkButton)
END_MESSAGE_MAP()
// Clogin1Dlg message handlers
BOOL Clogin1Dlg::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
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 Clogin1Dlg::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 Clogin1Dlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
void Clogin1Dlg::OnBnClickedOkButton()
{
// TODO: Add your control notification handler code here
UpdateData();
char UsernameFromFile[20], PasswordFromFile[20];
FILE *fleCredentials;
bool ValidLogin = false;
if(m_username == "" )
{
AfxMessageBox(_T("You must provide a username and a password or click Cancel"));
return;
}
if( m_password == "" )
{
AfxMessageBox(_T("Invalid Login"));
return;
}
try {
// Open the file for reading
fleCredentials = fopen("credentials.txt", "r");
// Scan the file from beginning to end
while( !feof(fleCredentials) )
{
//Read a username
fscanf(fleCredentials, "%s", UsernameFromFile);
//Compare the typed username with the username from the file
if(strcmp((LPCTSTR)m_username, UsernameFromFile) == 0 )
{
// With the current username, retrieve the corresponding password
fscanf(fleCredentials, "%s", PasswordFromFile);
//Compare the typed password with the one on file
if( strcmp((LPCTSTR)m_password, PasswordFromFile) == 0 )
{
ValidLogin = true;
}
else
ValidLogin = false;
}
}
if( ValidLogin == true )
OnOK();
else
{
AfxMessageBox(_T("Invalid Credentials. Please try again"));
//this->m_EditUsername.SetFocus();
}
fclose(fleCredentials);
}
catch(...)
{
AfxMessageBox(_T("Could not validate the credentials"));
}
UpdateData(FALSE);
}
But I got this error
Error 3 error C2664: 'strcmp' : cannot convert parameter 1 from 'LPCTSTR' to 'const char *' e:\win32\test\login1\login1dlg.cpp 130 1 login1
i want little help from u
try Change the 2 if statement code to this
if(strcmp((LPSTR)(LPCTSTR)m_username, UsernameFromFile) == 0 )
if( strcmp((LPSTR)(LPCTSTR)m_password, PasswordFromFile) == 0 )
from the error i can see cannot convert parameter 1 from 'LPCTSTR' to 'const char *'
strcmp is used with char ANSI but try using the Unicode version of it instead
as you know LPCTSTR is dependent on unicode or ansi if you use unicode library use the following function wcscmp for more information help at msdn
also for types windows data types on msdn
so you replace strcmp at line 129 and 135 with wcscmp if this solve the problem just let us know