MFC modeless dialog close immediately - c++

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.

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.

How to avoid flickering while the CScrollView is moving?

I was trying to make the CScrollView move
Although it moved successfully, but I found a problem...
The CScrollView flickered randomly while it is moving.
Below is the whole code of my project:
#include <afxwin.h>
#include <afxext.h>
#include "resource.h"
class MyView : public CScrollView
{
public:
void OnDraw(CDC *aDC){
CRect rc;
GetClientRect(&rc);
aDC->FillSolidRect(&rc, RGB(0,0,255));
}
BOOL PreCreateWindow(CREATESTRUCT& cs)
{
cs.style &= ~WS_BORDER;
return CScrollView::PreCreateWindow(cs);
}
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if(CScrollView::OnCreate(lpCreateStruct) == -1)
return -1;
CSize DCSize(200, 800);
SetScrollSizes(MM_TEXT, DCSize);
return 0;
}
DECLARE_DYNCREATE(MyView)
DECLARE_MESSAGE_MAP()
};
IMPLEMENT_DYNCREATE(MyView, CScrollView)
BEGIN_MESSAGE_MAP(MyView, CScrollView)
ON_WM_CREATE()
END_MESSAGE_MAP()
class CMainDlg : public CDialog
{
public:
CMainDlg(CWnd* pParent = NULL);
enum { IDD = IDD_MAIN_DIALOG };
CWnd* pFrameWnd;
CCreateContext context;
MyView* pView;
int time;
virtual BOOL OnInitDialog();
afx_msg void OnTimer(UINT_PTR timer);
void OnPaint(){
CPaintDC dc(this);
CRect rc;
GetClientRect(&rc);
dc.FillSolidRect(&rc,RGB(255,187,187));
}
DECLARE_MESSAGE_MAP()
};
BEGIN_MESSAGE_MAP(CMainDlg, CDialog)
ON_WM_TIMER()
ON_WM_PAINT()
END_MESSAGE_MAP()
CMainDlg::CMainDlg(CWnd* pParent /*=NULL*/)
: CDialog(CMainDlg::IDD, pParent)
{
}
BOOL CMainDlg::OnInitDialog()
{
CDialog::OnInitDialog();
pFrameWnd = this;
context.m_pCurrentDoc = NULL;
context.m_pNewViewClass = RUNTIME_CLASS(MyView);
pView = (MyView*)((CFrameWnd*)pFrameWnd)->CreateView(&context);
pView->ShowWindow(SW_SHOW);
time = 0;
SetTimer(1, 1, 0);
return TRUE;
}
void CMainDlg::OnTimer(UINT_PTR timer)
{
if(timer == 1){
if(time > 300){
KillTimer(1);
return;
}
pView->MoveWindow(CRect(time,10,time+300,200),FALSE);
}
time+=1;
Invalidate(FALSE);
}
class MyApp : public CWinApp
{
public:
BOOL InitInstance()
{
CWinApp::InitInstance();
CMainDlg Frame;
Frame.DoModal();
return true;
}
} a_app;
I don't know why the CScrollView flickered while it is moving. Can anyone solve this problem?
It is flickering because you're invalidating the entire window. This causes a WM_ERASE, which blanks the window, then a WM_PAINT, which redraws the entire thing. You're passing FALSE as the bRepaint (last) parameter to MoveWindow, so that it won't repaint any necessary window area after the window has been moved.
Normally when a window moves the content moves with it, and the only parts that need to be redrawn are bits that were offscreen or under another window. Passing TRUE as the last parameter will cause only these areas of the window to be redrawn, which will avoid the flicker.

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.

Where I can define a global variable in an MFC application?

I want to declare a global variable inside an MFC application, so that every action inside the application can see this variable and manipulate it, but I don't know where exactly I can declare that variable. in this code i have many button actions, i need to declare a string variable that's shared among this actions.
// CalculatorDlg.cpp : implementation file
//
#include "stdafx.h"
#include "Calculator.h"
#include "CalculatorDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CAboutDlg dialog used for App About
class CAboutDlg : public CDialog
{
public:
CAboutDlg();
// Dialog Data
enum { IDD = IDD_ABOUTBOX };
public:
static CString myValue;
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()
// CCalculatorDlg dialog
CCalculatorDlg::CCalculatorDlg(CWnd* pParent /*=NULL*/)
: CDialog(CCalculatorDlg::IDD, pParent)
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CCalculatorDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CCalculatorDlg, CDialog)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
//}}AFX_MSG_MAP
ON_BN_CLICKED(IDC_BUTTON1, &CCalculatorDlg::OnBnClickedButton1)
ON_BN_CLICKED(IDC_BUTTON3, &CCalculatorDlg::OnBnClickedButton3)
ON_BN_CLICKED(IDC_BUTTON2, &CCalculatorDlg::OnBnClickedButton2)
ON_BN_CLICKED(IDC_BUTTON6, &CCalculatorDlg::OnBnClickedButton6)
ON_BN_CLICKED(IDC_BUTTON5, &CCalculatorDlg::OnBnClickedButton5)
ON_BN_CLICKED(IDC_BUTTON4, &CCalculatorDlg::OnBnClickedButton4)
ON_BN_CLICKED(IDC_BUTTON9, &CCalculatorDlg::OnBnClickedButton9)
ON_BN_CLICKED(IDC_BUTTON8, &CCalculatorDlg::OnBnClickedButton8)
ON_BN_CLICKED(IDC_BUTTON7, &CCalculatorDlg::OnBnClickedButton7)
END_MESSAGE_MAP()
// CCalculatorDlg message handlers
BOOL CCalculatorDlg::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
return TRUE; // return TRUE unless you set the focus to a control
}
void CCalculatorDlg::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 CCalculatorDlg::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 CCalculatorDlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
void CCalculatorDlg::OnBnClickedButton1()
{
/*
CString s="ABC";
LPCTSTR str_name = _T("Hello ")*/;
SetDlgItemText(IDC_EDIT1,_T"9");
/*CAboutDlg::myValue="9";*/
}
void CCalculatorDlg::OnBnClickedButton3(){}
void CCalculatorDlg::OnBnClickedButton2(){}
void CCalculatorDlg::OnBnClickedButton6(){}
void CCalculatorDlg::OnBnClickedButton5(){}
void CCalculatorDlg::OnBnClickedButton4(){}
void CCalculatorDlg::OnBnClickedButton9(){}
void CCalculatorDlg::OnBnClickedButton8(){}
void CCalculatorDlg::OnBnClickedButton7(){}
If your project uses precompiled headers (with 99.9999% probability it uses it as default MFC project setting), you can declare this variable in precompiled header file, typically its name is stdafx.h and define it in global scope of any appropriate translation unit (.cpp file). Typically this could be YourProjectName.cpp file that contains application class derived from CWinApp.
// stdafx.h
extern int globalVar; // Global variable declaration, note extern keyword
// YourProjectName.cpp - global scope
int globalVar = 42; // Global variable definition
Precompiled header stdafx.h is included first in every .cpp file of project, so globalVar will be available everywhere in your project code.
Also would like to mention that global objects are not recommended to be used, it's considered as bad design and anti-pattern.
Put the global variable in a header file and add it to Name Forced Include File.