Error running a newly created MFC project - c++

I created an MFC project in Visual Studio and tried to run it but it got the error as shown in the picture.
this is the code:
#include "pch.h" #include "framework.h" #include "MFCApplication1.h"
#include "ChildFrm.h"
#ifdef _DEBUG #define new DEBUG_NEW #endif
// CChildFrame
IMPLEMENT_DYNCREATE(CChildFrame, CMDIChildWndEx)
BEGIN_MESSAGE_MAP(CChildFrame, CMDIChildWndEx)
ON_COMMAND(ID_FILE_PRINT, &CChildFrame::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_DIRECT, &CChildFrame::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_PREVIEW, &CChildFrame::OnFilePrintPreview)
ON_UPDATE_COMMAND_UI(ID_FILE_PRINT_PREVIEW, &CChildFrame::OnUpdateFilePrintPreview) END_MESSAGE_MAP()
// CChildFrame construction/destruction
CChildFrame::CChildFrame() noexcept { // TODO: add member initialization code here }
CChildFrame::~CChildFrame() { }
BOOL CChildFrame::PreCreateWindow(CREATESTRUCT& cs) { // TODO: Modify the Window class or styles here by modifying the CREATESTRUCT cs if( !CMDIChildWndEx::PreCreateWindow(cs) ) return FALSE;
cs.style = WS_CHILD | WS_VISIBLE | WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | FWS_ADDTOTITLE | WS_THICKFRAME;
return TRUE; }
// CChildFrame diagnostics
#ifdef _DEBUG void CChildFrame::AssertValid() const { CMDIChildWndEx::AssertValid(); }
void CChildFrame::Dump(CDumpContext& dc) const {
CMDIChildWndEx::Dump(dc); } #endif //_DEBUG
// CChildFrame message handlers
void CChildFrame::OnFilePrint() { if (m_dockManager.IsPrintPreviewValid()) { PostMessage(WM_COMMAND, AFX_ID_PREVIEW_PRINT); } }
void CChildFrame::OnFilePrintPreview() { if (m_dockManager.IsPrintPreviewValid()) { PostMessage(WM_COMMAND, AFX_ID_PREVIEW_CLOSE); // force Print Preview mode closed } }
void CChildFrame::OnUpdateFilePrintPreview(CCmdUI* pCmdUI) {
pCmdUI->SetCheck(m_dockManager.IsPrintPreviewValid()); }
An error dialog appears
[ Unable to start program C:\Users\PC\Desktop\WindownsProject1\Debug\MFCApplication1.exe'. The system cannot find the file specified.]
[1]: https://i.stack.imgur.com/hvCiX.png [2]: https://i.stack.imgur.com/Kib9c.jpg

The program fails to build, so the executable is not created. That's why it can't be started.
From your screenshots it appears that you don't have MFC installed as part of visual studio. So you should launch visual studio installer and install the MFC component, then try again.

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.

Reduced label is displayed in c++ mfc application

I develop some C++ MFC application. In my dialog box there is a progress bar and one label with constant text (cyrillic symbols).
On Windows 7,XP this text is displayed good but on Windows 8,10 it is displayed in reduced form.
Why?
This is on Windows 7:
And this is on Windows 8:
This is a source code of the class related to this Dialog Form.
*.cpp file:
// Progress.cpp : implementation file
//
#include "stdafx.h"
#include "LybidLoader.h"
#include "Progress.h"
#include "afxdialogex.h"
// Progress dialog
IMPLEMENT_DYNAMIC(Progress, CDialogEx)
Progress::Progress(CWnd* pParent /*=NULL*/)
: CDialogEx(Progress::IDD, pParent)
{
}
Progress::~Progress()
{
}
void Progress::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
DDX_Control(pDX, IDC_PROGRESS1, m_ProgressBar);
}
BEGIN_MESSAGE_MAP(Progress, CDialogEx)
ON_BN_CLICKED(IDC_BUTTON1, &Progress::OnBnClickedForceExit)
END_MESSAGE_MAP()
// Progress message handlers
BOOL Progress::OnInitDialog()
{
CDialogEx::OnInitDialog();
ModifyStyle( WS_SYSMENU, 0);
m_ProgressBar.SetMarquee(TRUE, 10);
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
void Progress::OnBnClickedForceExit()
{
if (::MessageBoxW(this->m_hWnd, (LPCWSTR)_T("Ви впевнені? Буде здійснено аварійний вихід"), (LPCWSTR)_T("Підтвердіть дію"), MB_ICONEXCLAMATION | MB_YESNO) == IDYES)
{
PostQuitMessage(0);
}
}
BOOL Progress::PreTranslateMessage(MSG* pMsg)
{
// TODO: Add your specialized code here and/or call the base class
if( pMsg->message == WM_KEYDOWN )
{
if(pMsg->wParam == VK_RETURN || pMsg->wParam == VK_ESCAPE)
{
return TRUE; // Do not process further
}
}
return CDialogEx::PreTranslateMessage(pMsg);
}
And *.h file:
#pragma once
#include "afxcmn.h"
// Progress dialog
class Progress : public CDialogEx
{
DECLARE_DYNAMIC(Progress)
public:
Progress(CWnd* pParent = NULL); // standard constructor
virtual ~Progress();
// Dialog Data
enum { IDD = IDD_PROGRESSBAR };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
DECLARE_MESSAGE_MAP()
public:
virtual BOOL OnInitDialog();
CProgressCtrl m_ProgressBar;
afx_msg void OnBnClickedForceExit();
virtual BOOL PreTranslateMessage(MSG* pMsg);
};
And this is a portion of resources file:
IDD_PROGRESSBAR DIALOGEX 0, 0, 369, 105
STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_VISIBLE | WS_CAPTION | WS_SYSMENU
CAPTION "Будь-ласка, зачекайте!"
FONT 8, "Microsoft Sans Serif", 400, 0, 0x1
BEGIN
CONTROL "",IDC_PROGRESS1,"msctls_progress32",PBS_MARQUEE | WS_BORDER,7,47,355,14
LTEXT "Триває обмін даними з опціональною платою! НЕ ВИМИКАЙТЕ РАДІОСТАНЦІЮ",IDC_STATIC,25,19,267,8
PUSHBUTTON "Примусово завершити роботу",IDC_BUTTON1,101,84,118,14
END
Disregard the garbage characters in the following images, it's just a codepage issue.
The space you provide for the static text controls too small:
The first dialog is yours, modify it so that it looks like the second one.
It could be font DPI, or it could be fonts themselves. It could be "Microsoft Sans Serif" maps to a different font. I have worked enough localization to know that some fonts are not available on all systems. I would think that "Microsoft Sans Serif" would probably be, but I have seen systems in the Far East where "Arial" was not on the system.
If I were you, I would change "Microsoft Sans Serif" to "MS Shell Dlg" in your dialog resource. "MS Shell Dlg" is sort of a virtual font that maps roughly to the default GUI font.

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.

MFC modeless dialog close immediately

I like to write a modeless dialog based app, but I have a problem. When the program starts, the window close immediately.
The same code works fine when I make a modal dialog. (DoModal())
Csetkliens.h
#pragma once
#ifndef __AFXWIN_H__
#error "include 'stdafx.h' before including this file for PCH"
#endif
#include "resource.h" // main symbols
#include "CsetkliensDlg.h"
class CCsetkliensApp : public CWinApp
{
public:
CCsetkliensApp();
virtual BOOL InitInstance();
DECLARE_MESSAGE_MAP()
private:
CCsetkliensDlg* dlg;
};
extern CCsetkliensApp theApp;
Csetkliens.cpp
#include "stdafx.h"
#include "Csetkliens.h"
#include "CsetkliensDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
BEGIN_MESSAGE_MAP(CCsetkliensApp, CWinApp)
ON_COMMAND(ID_HELP, &CWinApp::OnHelp)
END_MESSAGE_MAP()
CCsetkliensApp::CCsetkliensApp()
{
dlg = NULL;
}
CCsetkliensApp theApp;
BOOL CCsetkliensApp::InitInstance()
{
INITCOMMONCONTROLSEX InitCtrls;
InitCtrls.dwSize = sizeof(InitCtrls);
InitCtrls.dwICC = ICC_WIN95_CLASSES;
InitCommonControlsEx(&InitCtrls);
CWinApp::InitInstance();
if (!AfxSocketInit())
{
AfxMessageBox(IDP_SOCKETS_INIT_FAILED);
return FALSE;
}
CShellManager *pShellManager = new CShellManager;
dlg = new CCsetkliensDlg();
m_pMainWnd = dlg;
dlg->Create(CCsetkliensDlg::IDD);
dlg->ShowWindow(SW_SHOW);
if (pShellManager != NULL)
{
delete pShellManager;
}
return FALSE;
}
CsetkliensDlg.h
#pragma once
#include "ConnectDlg.h"
class CCsetkliensDlg : public CDialogEx
{
public:
CCsetkliensDlg(CWnd* pParent = NULL);
enum { IDD = IDD_CSETKLIENS_DIALOG };
protected:
virtual BOOL OnInitDialog();
DECLARE_MESSAGE_MAP()
};
CsetkliensDlg.cpp
#include "stdafx.h"
#include "Csetkliens.h"
#include "CsetkliensDlg.h"
#include "afxdialogex.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
CCsetkliensDlg::CCsetkliensDlg(CWnd* pParent /*=NULL*/)
: CDialogEx(CCsetkliensDlg::IDD, pParent)
{
}
BEGIN_MESSAGE_MAP(CCsetkliensDlg, CDialogEx)
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
END_MESSAGE_MAP()
BOOL CCsetkliensDlg::OnInitDialog()
{
CDialogEx::OnInitDialog();
return TRUE;
}
Returning FALSE from your application class's InitInstance method tells MFC that initialization failed and the application should terminate.
Change that like to return TRUE; and everything should work fine.
BOOL CCsetkliensApp::InitInstance()
{
INITCOMMONCONTROLSEX InitCtrls;
InitCtrls.dwSize = sizeof(InitCtrls);
InitCtrls.dwICC = ICC_WIN95_CLASSES;
InitCommonControlsEx(&InitCtrls);
CWinApp::InitInstance();
if (!AfxSocketInit())
{
AfxMessageBox(IDP_SOCKETS_INIT_FAILED);
return FALSE;
}
CShellManager *pShellManager = new CShellManager;
dlg = new CCsetkliensDlg();
m_pMainWnd = dlg;
dlg->Create(CCsetkliensDlg::IDD);
dlg->ShowWindow(SW_SHOW); // this is not a blocking call!
if (pShellManager != NULL)
{
delete pShellManager;
}
return TRUE; // change this one!
}
The reason that it works with a modal dialog (shown by calling the DoModal method) is because a modal dialog creates its own message loop, which runs until you close the dialog. That means that execution effectively "blocks" at the DoModal call without returning control to your InitInstance method, so it doesn't return FALSE and MFC doesn't quit. At least not until you close the dialog, in which case you want it to quit, so everything appears the work.
I'm not seeing anything that tells the application to stay alive after opening the modeless window. You need at least one 'modal' style window, or something else to control termination of the application.