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

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.

Related

Spin Control GetPos() value is delayed

I have an edit control buddied with a spin control with the initial position set to 0. When the up arrow is clicked the edit box goes from 0 to 1, which is fine. But when I use GetPos() the MyValue is 0. When the spin control is incremented again from 1 to 2, the MyValue becomes 1. When down arrow is pressed the edit box goes from 2 to 1, but the value becomes 2. It seems that the MyValue is always one action behind the spin control.
BOOL CAlphaDlg::OnInitDialog()
{
// default code left out to keep it short ...
// TODO: Add extra initialization here
// set range and initial position
mSpinControl.SetRange(0, 3600); // range
mSpinControl.SetPos(0); // inital position
MyValue = mSpinControl.GetPos();
// display initial value in buddy editcontrol
mEditControlDisplay.Format("%d", MyValue);
UpdateData(false);
return TRUE;
}
void CAlphaDlg::OnDeltaposSpin1(NMHDR *pNMHDR, LRESULT *pResult)
{
LPNMUPDOWN pNMUpDown = reinterpret_cast<LPNMUPDOWN>(pNMHDR);
// TODO: Add your control notification handler code here
UpdateData(true);
int MyValue= mSpinControl.GetPos();
std::cout << MyValue << std::endl;
*pResult = 0;
}
I have tried getting the value from the editcontrol but the value is exhibiting the same behavior. How do I get the value of the GetPos() to match what is showing in the edit control?
Thank you in advance.
edit: Here is the full code
// AlphaDlg.cpp : implementation file
//
#include "stdafx.h"
#include "Alpha.h"
#include "AlphaDlg.h"
#include "afxdialogex.h"
#include <iostream>
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CAboutDlg dialog used for App About
class CAboutDlg : public CDialogEx
{
public:
CAboutDlg();
// Dialog Data
#ifdef AFX_DESIGN_TIME
enum { IDD = IDD_ABOUTBOX };
#endif
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
// Implementation
protected:
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX)
{
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()
// CAlphaDlg dialog
CAlphaDlg::CAlphaDlg(CWnd* pParent /*=NULL*/)
: CDialogEx(IDD_ALPHA_DIALOG, pParent)
, mEditControlDisplay(_T(""))
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CAlphaDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
DDX_Text(pDX, IDC_EDIT1, mEditControlDisplay);
DDX_Control(pDX, IDC_SPIN1, mSpinControl);
}
BEGIN_MESSAGE_MAP(CAlphaDlg, CDialogEx)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_NOTIFY(UDN_DELTAPOS, IDC_SPIN1, &CAlphaDlg::OnDeltaposSpin1)
END_MESSAGE_MAP()
// CAlphaDlg message handlers
BOOL CAlphaDlg::OnInitDialog()
{
CDialogEx::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)
{
BOOL bNameValid;
CString strAboutMenu;
bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
ASSERT(bNameValid);
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
mSpinControl.SetRange(0, 10);
mSpinControl.SetPos(0);
int MyValue = mSpinControl.GetPos();
mEditControlDisplay.Format("%d", MyValue);
UpdateData(false);
return TRUE; // return TRUE unless you set the focus to a control
}
void CAlphaDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialogEx::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 CAlphaDlg::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 CAlphaDlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
void CAlphaDlg::OnDeltaposSpin1(NMHDR *pNMHDR, LRESULT *pResult)
{
LPNMUPDOWN pNMUpDown = reinterpret_cast<LPNMUPDOWN>(pNMHDR);
// TODO: Add your control notification handler code here
*pResult = 0;
UpdateData(true);
int MyValue = mSpinControl.GetPos();
std::cout << mEditControlDisplay << std::endl;
std::cout << MyValue << std::endl;
}
Firstly, consider mapping your edit box to a int and then you do not need to cast to a string. And the default value is 0 to begin with so the spinner will be OK. You can also switch off the auto buddy.
In the deltapos handler you could do this:
void CMFCApplication1Dlg::OnDeltaposSpin1(NMHDR *pNMHDR, LRESULT *pResult)
{
LPNMUPDOWN pNMUpDown = reinterpret_cast<LPNMUPDOWN>(pNMHDR);
// TODO: Add your control notification handler code here
*pResult = 0;
SetDlgItemInt(IDC_EDIT1, pNMUpDown->iPos);
UpdateData(TRUE);
CString a;
a.Format(_T("%d"), iNumberValue);
AfxMessageBox(a);
}
For me the results in the popup message and the edit control are the same.
Update
You can workout what the new value would be by looking at the structure:
void CMFCApplication1Dlg::OnDeltaposSpin1(NMHDR *pNMHDR, LRESULT *pResult)
{
LPNMUPDOWN pNMUpDown = reinterpret_cast<LPNMUPDOWN>(pNMHDR);
int iCurrentPos = pNMUpDown->iPos;
if (pNMUpDown->iDelta > 0)
iCurrentPos++;
else
iCurrentPos--;
CString strNewValue;
strNewValue.Format(_T("%d"), iCurrentPos);
AfxMessageBox(strNewValue);
*pResult = 0;
}
For Consideration
You might want to give some thought to CSpinButtonCtrl::SetAccel which sets the acceleration for a spin button control.
In your case I don't think it is going to matter because your range is only 10
units. But if you had a larger range then it is possible that it would increment by more than one unit. It is just something to keep in mind.
According to this reference for UDN_DELTAPOS it says:
The iDelta member of the structure is a signed integer that contains the proposed change in position.
So you could improve the code and increment/decrement based on the iDelta value instead of 1. This would factor in for acceleration. So:
int iCurrentPos = pNMUpDown->iPos + pNMUpDown->iDelta;

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.

Having trouble by MFC lntelliSense on C++

Hello I have this Microsoft Foundation Classes that will run mostly and check USB Device and other stuff. The problem is, certain IntelliSense is undefined that's why most errors will display when running the program.
Here's the error list:
The Entire Code:
// MFCApplication2Dlg.cpp : implementation file
//
#include "stdafx.h"
#include "MFCApplication2.h"
#include "MFCApplication2Dlg.h"
#include "afxdialogex.h"
#include "afxwin.h"
#include "CyAPI.h"
#define UART_H
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
bool IsConnect = false;
// CAboutDlg dialog used for App About
class CAboutDlg : public CDialogEx
{
public:
CAboutDlg();
// Dialog Data
enum { IDD = IDD_ABOUTBOX };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
// Implementation
protected:
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialogEx(CAboutDlg::IDD)
{
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()
// CMFCApplication2Dlg dialog
CMFCApplication2Dlg::CMFCApplication2Dlg(CWnd* pParent /*=NULL*/)
: CDialogEx(CMFCApplication2Dlg::IDD, pParent)
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CMFCApplication2Dlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CMFCApplication2Dlg, CDialogEx)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDC_BUTTON1, &CMFCApplication2Dlg::OnBnClickedButton1)
ON_BN_CLICKED(IDC_BUTTON3, &CMFCApplication2Dlg::OnBnClickedButton3)
ON_BN_CLICKED(IDC_BUTTON2, &CMFCApplication2Dlg::OnBnClickedButton2)
END_MESSAGE_MAP()
// CMFCApplication2Dlg message handlers
BOOL CMFCApplication2Dlg::OnInitDialog()
{
CDialogEx::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)
{
BOOL bNameValid;
CString strAboutMenu;
bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
ASSERT(bNameValid);
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 CMFCApplication2Dlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialogEx::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 CMFCApplication2Dlg::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 CMFCApplication2Dlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
bool CMFCApplication2Dlg::OnBnClickedButton1()
{
USBDevice->Open(0);
if (USBDevice->IsOpen() != TRUE)
{
AfxMessageBox(_T("Failed to Open Device"));
return false;
}
else
{
IsConnect = true;
return true;
}
}
void CMFCApplication2Dlg::OnBnClickedButton3()
{
USBDevice->Close();
IsConnect = false;
}
void CMFCApplication2Dlg::OnBnClickedButton2()
{
char tmpUart[60];
long OutPacketSize;
OutPacketSize = sizeof(sUart);
LPTSTR pBuffer;
CString sBuffer;
int i;
if (IsConnect == false)
{
AfxMessageBox(_T("USB Connect Fail"));
return;
}
CEdit*OutValue = (CEdit*)GetDlgItem(IDC_OUT_VALUE);
pBuffer = sBuffer.GetBuffer(60);
OutValue->GetWindowText(pBuffer, 60);
strcpy(tmpUart, pBuffer);
OutPacketSize = strlen(tmpUart);
for (i = 0; i<OutPacketSize; i++) sUart[i] = tmpUart[i];
sUart[OutPacketSize + 1] = 0;
OutPacketSize = OutPacketSize + 1;
//Perform the BULK OUT
if (USBDevice->BulkOutEndPt)
{
USBDevice->BulkOutEndPt->XferData(sUart, OutPacketSize);
}
}
HELP:
What certain libraries do I have to import or include to fix these kind of errors? I'm new to MFC's and I don't quite yet understand the structures and ways to program this. Please help.
The ON_BN_CLICKED message map macro expects a member function pointer with the signature
afx_msg void memberFxn()
However, your OnBnClickedButton1 returns a bool. That member function must not have a return value (void) to use it with ON_BN_CLICKED.

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
}