I wrote a code in mfc for login form
my code is here
// login1Dlg.cpp : implementation file
//
#include "stdafx.h"
#include "login1.h"
#include "login1Dlg.h"
#include "afxdialogex.h"
//#include "LOGINDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// Clogin1Dlg dialog
Clogin1Dlg::Clogin1Dlg(CWnd* pParent /*=NULL*/)
: CDialogEx(Clogin1Dlg::IDD, pParent)
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
m_username = _T("");
m_password = _T("");
}
void Clogin1Dlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
DDX_Text(pDX, IDC_USERNAME_EDIT, m_username);
DDX_Text(pDX, IDC_PASSWORD_EDIT, m_password);
}
BEGIN_MESSAGE_MAP(Clogin1Dlg, CDialogEx)
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDC_OK_BUTTON, &Clogin1Dlg::OnBnClickedOkButton)
END_MESSAGE_MAP()
// Clogin1Dlg message handlers
BOOL Clogin1Dlg::OnInitDialog()
{
CDialogEx::OnInitDialog();
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
// TODO: Add extra initialization here
return TRUE; // return TRUE unless you set the focus to a control
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
void Clogin1Dlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialogEx::OnPaint();
}
}
// The system calls this function to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR Clogin1Dlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
void Clogin1Dlg::OnBnClickedOkButton()
{
// TODO: Add your control notification handler code here
UpdateData();
char UsernameFromFile[20], PasswordFromFile[20];
FILE *fleCredentials;
bool ValidLogin = false;
if(m_username == "" )
{
AfxMessageBox(_T("You must provide a username and a password or click Cancel"));
return;
}
if( m_password == "" )
{
AfxMessageBox(_T("Invalid Login"));
return;
}
try {
// Open the file for reading
fleCredentials = fopen("credentials.txt", "r");
// Scan the file from beginning to end
while( !feof(fleCredentials) )
{
//Read a username
fscanf(fleCredentials, "%s", UsernameFromFile);
//Compare the typed username with the username from the file
if(strcmp((LPCTSTR)m_username, UsernameFromFile) == 0 )
{
// With the current username, retrieve the corresponding password
fscanf(fleCredentials, "%s", PasswordFromFile);
//Compare the typed password with the one on file
if( strcmp((LPCTSTR)m_password, PasswordFromFile) == 0 )
{
ValidLogin = true;
}
else
ValidLogin = false;
}
}
if( ValidLogin == true )
OnOK();
else
{
AfxMessageBox(_T("Invalid Credentials. Please try again"));
//this->m_EditUsername.SetFocus();
}
fclose(fleCredentials);
}
catch(...)
{
AfxMessageBox(_T("Could not validate the credentials"));
}
UpdateData(FALSE);
}
But I got this error
Error 3 error C2664: 'strcmp' : cannot convert parameter 1 from 'LPCTSTR' to 'const char *' e:\win32\test\login1\login1dlg.cpp 130 1 login1
i want little help from u
try Change the 2 if statement code to this
if(strcmp((LPSTR)(LPCTSTR)m_username, UsernameFromFile) == 0 )
if( strcmp((LPSTR)(LPCTSTR)m_password, PasswordFromFile) == 0 )
from the error i can see cannot convert parameter 1 from 'LPCTSTR' to 'const char *'
strcmp is used with char ANSI but try using the Unicode version of it instead
as you know LPCTSTR is dependent on unicode or ansi if you use unicode library use the following function wcscmp for more information help at msdn
also for types windows data types on msdn
so you replace strcmp at line 129 and 135 with wcscmp if this solve the problem just let us know
Related
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;
I am trying to display a GIF picture as splash as starting of my small program in visual studio. I am really getting crazy. I looked it is possible in Qt IDE but I really need it in visual studio because my other code works only with visual studio. And yes I tried to convert my code for Qt giving me too many errors.
I have seen this post.
I am using GDI+ but still dunno how to simply display it instead of play and stop. It's okay even instead of splash to display a small form that plays the GIF file, can you guys give me a small code snippet in how to do it in c++?
Thanks.
Here is an MFC window class that implements a splash screen using GDI Plus for displaying an (animated) GIF.
I've encapsulated everything inside a header file to simplify using it with your project. Save it as an .h file (maybe "SplashWnd.h"), then include it wherever you want to set up the splash. You app's InitInstance might be a good place to add it - something like this line (before any DoModal calls):
SplashWnd splash(_T("Filname.gif"));
The constructor can also take parameters for controlling the delay before auto-closing, and also specifying a function to call when the splash is closed.
The splash window has no border or caption - it appears only as the loaded image, floating on top of any other windows. Its icon doesn't appear in the taskbar, and will close when its timeout expires, or the user clicks the window or presses a key.
#pragma once
#include <functional>
#include <afxwin.h>
#include <gdiplus.h>
#pragma comment(lib,"gdiplus.lib")
inline void ManageGdiPlusInit(bool release=false) {
static int refcount = 0;
static ULONG_PTR token;
if(release) {
if(--refcount == 0) {
Gdiplus::GdiplusShutdown(token);
}
} else if(++refcount == 1) {
Gdiplus::GdiplusStartupInput startup_input;
Gdiplus::GdiplusStartup(&token, &startup_input, 0);
} }
inline void GdiPlusInit() { ManageGdiPlusInit(false); }
inline void GdiPlusRelease() { ManageGdiPlusInit(true); }
namespace {
class SplashWnd : public CWnd {
protected:
static CString WindowClass() {
static CString name;
if(name.IsEmpty()) {
name = AfxRegisterWndClass(CS_DROPSHADOW, 0, (HBRUSH)GetStockObject(GRAY_BRUSH), 0);
}
return name;
}
Gdiplus::Image *m_pImage;
UINT m_FrameCount;
unsigned char *m_FrameDelayData;
const UINT *m_FrameDelays;
UINT m_CurFrameIndex;
UINT m_AnimationTimerId;
UINT m_ExpireTimerId;
CRect m_WindowRect;
std::function<void()> m_DismissCallback;
DECLARE_MESSAGE_MAP()
afx_msg void OnLButtonDown(UINT nFlags, CPoint point) {
DestroyWindow();
}
afx_msg void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags) {
DestroyWindow();
}
afx_msg void OnDestroy() {
if(m_AnimationTimerId != UINT(-1)) {
KillTimer(m_AnimationTimerId);
}
if(m_ExpireTimerId != UINT(-1)) {
KillTimer(m_ExpireTimerId);
}
if(m_DismissCallback) {
m_DismissCallback();
}
CWnd::OnDestroy();
}
afx_msg void OnTimer(UINT nIDEvent) {
if(nIDEvent == m_AnimationTimerId) {
if(++m_CurFrameIndex >= m_FrameCount) {
m_CurFrameIndex = 0;
}
DrawCurFrame();
KillTimer(m_AnimationTimerId);
m_AnimationTimerId = SetTimer(1, m_FrameDelays[m_CurFrameIndex], 0);
return;
}
if(nIDEvent == m_ExpireTimerId) {
DestroyWindow();
return;
} }
void PostNcDestroy() {
if(m_DeleteSelf) {
delete this;
}
}
void DrawCurFrame() {
Gdiplus::Graphics g(m_hWnd);
GUID dim_select_id = Gdiplus::FrameDimensionTime;
m_pImage->SelectActiveFrame(&dim_select_id, m_CurFrameIndex);
g.DrawImage(m_pImage, 0, 0, m_WindowRect.Width(), m_WindowRect.Height());
}
public:
// set m_DeleteSelf to true if a SplashWnd is created with new, and you want it to
// auto-delete itself when the window expires or is dismissed.
bool m_DeleteSelf;
// file_path the gif file path
// ExpireMs the time, in milliseconds until the window automatically closes itself
// WidthFactor the fraction of the width of the primary display to use as the splash screen's width
// HeightFactor the fraction of the height of the primary display to use as the height
// If WidthFactor or HeightFactor are 0, the original image aspect ratio is preserved
// If both are 0, the original image size, in pixels is used
SplashWnd(CString file_path, DWORD ExpireMs=2000, double WidthFactor=0.4, double HeightFactor=0) {
GdiPlusInit();
m_pImage = new Gdiplus::Image(file_path);
// Set up an array of frame times for animated images
UINT dimension_count = m_pImage->GetFrameDimensionsCount();
GUID dimension_id;
m_pImage->GetFrameDimensionsList(&dimension_id, 1);
m_FrameCount = m_pImage->GetFrameCount(&dimension_id);
UINT frame_delay_size = m_pImage->GetPropertyItemSize(PropertyTagFrameDelay);
m_FrameDelayData = new unsigned char[frame_delay_size];
Gdiplus::PropertyItem* frame_delay_item = reinterpret_cast<Gdiplus::PropertyItem*>(m_FrameDelayData);
m_pImage->GetPropertyItem(PropertyTagFrameDelay, frame_delay_size, frame_delay_item);
m_FrameDelays = reinterpret_cast<const UINT*>(frame_delay_item->value);
// Figure out the size and location of the splash window
int primary_width = GetSystemMetrics(SM_CXFULLSCREEN);
int primary_height = GetSystemMetrics(SM_CYFULLSCREEN);
int splash_width = int(primary_width * WidthFactor);
int splash_height = int(primary_height * HeightFactor);
if(splash_width == 0) {
if(splash_height == 0) {
splash_width = m_pImage->GetWidth();
splash_height = m_pImage->GetHeight();
} else {
splash_width = primary_width * splash_height / primary_height;
}
} else if(splash_height == 0) {
splash_height = primary_height * splash_width / primary_width;
}
int l = (primary_width - splash_width) / 2;
int t = (primary_height - splash_height) / 2;
int r = l + splash_width;
int b = t + splash_height;
m_WindowRect.SetRect(
(primary_width - splash_width) / 2,
(primary_height - splash_height) / 2,
(primary_width + splash_width) / 2,
(primary_height + splash_height) / 2);
// WS_EX_TOPMOST makes the window cover up other, regular windows
// WS_EX_TOOLWINDOW prevents an icon for this window in the taskbar
// WS_POPUP prevents caption and border from being drawn
CreateEx(WS_EX_TOPMOST | WS_EX_TOOLWINDOW, WindowClass(), _T("Splash"), WS_VISIBLE | WS_POPUP, m_WindowRect, 0, 0);
// Show the first frame
m_CurFrameIndex = 0;
DrawCurFrame();
// Set up the frame-flipping animation timer
m_ExpireTimerId = m_AnimationTimerId = UINT(-1);
if(m_FrameCount > 1) {
m_AnimationTimerId = SetTimer(1, m_FrameDelays[m_CurFrameIndex], 0);
}
// Set up the expiration timer
if(ExpireMs != INFINITE) {
m_ExpireTimerId = SetTimer(2, ExpireMs, 0);
}
m_DeleteSelf = false;
}
// Constructor which takes a callback function which will be called when the splash window closes
template <typename F>
SplashWnd(CString file_path, DWORD ExpireMs, double WidthFactor, double HeightFactor, F DismissCallback)
: SplashWnd(file_path, ExpireMs, WidthFactor, HeightFactor)
{
m_DismissCallback = DismissCallback;
}
~SplashWnd() {
delete [] m_FrameDelayData;
delete m_pImage;
GdiPlusRelease();
}
};
// Message map, usually in an implementation file, but here encapsulated inside the header
// using an anonymous namespace to prevent possible ODR problems.
BEGIN_MESSAGE_MAP(SplashWnd, CWnd)
ON_WM_KEYDOWN()
ON_WM_LBUTTONDOWN()
ON_WM_TIMER()
ON_WM_DESTROY()
END_MESSAGE_MAP()
}
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.
I have two variables, m_GridSize and m_TimeDisplay, which update themselves according to a variable called "world" here. Now, the MFC program will display the words "Grid size: " and "Time: ", but it will not display the actual values of the doubles. I am using Visual Studio Community 2013 to make a Win32 GUI application.
I am having trouble with the CString Format function.
EDIT to include full code:
// smart_parking_guiDlg.cpp : implementation file
//
#include "stdafx.h"
#include "smart_parking_gui.h"
#include "smart_parking_guiDlg.h"
#include "afxdialogex.h"
#include "Cadd_Destination.h"
#include "Cadd_Lot.h"
#include "Cadd_Driver.h"
#include "Commands.h" // Used to handle commands
#include "Grid.h" // Contains the grid
#include <string>
#include <io.h>
#include <fcntl.h>
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// Csmart_parking_guiDlg dialog
Csmart_parking_guiDlg::Csmart_parking_guiDlg(CWnd* pParent /*=NULL*/)
: CDialogEx(Csmart_parking_guiDlg::IDD, pParent)
, m_EchoSize(_T("Grid size: "))
, m_EchoTime(_T("Time: "))
, m_EchoStatus(_T("Open"))
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
this->world = new Grid(10, 5); // default grid
}
void Csmart_parking_guiDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
DDX_Text(pDX, IDC_ST_GRIDSIZE, m_EchoSize);
DDX_Text(pDX, IDC_ST_TIME, m_EchoTime);
DDX_Text(pDX, IDC_ST_STATUS, m_EchoStatus);
}
BEGIN_MESSAGE_MAP(Csmart_parking_guiDlg, CDialogEx)
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDC_B_OPEN_CONFIG, &Csmart_parking_guiDlg::OnBnClickedBOpenConfig)
ON_BN_CLICKED(IDC_B_SAVECONFIG, &Csmart_parking_guiDlg::OnBnClickedBSaveconfig)
ON_BN_CLICKED(IDC_B_NEXTEVENT, &Csmart_parking_guiDlg::OnBnClickedBNextevent)
ON_BN_CLICKED(IDC_B_NEWDEST, &Csmart_parking_guiDlg::OnBnClickedBNewdest)
ON_BN_CLICKED(IDC_B_NEWLOT, &Csmart_parking_guiDlg::OnBnClickedBNewlot)
ON_BN_CLICKED(IDC_B_NEWDRIVER, &Csmart_parking_guiDlg::OnBnClickedBNewdriver)
ON_BN_CLICKED(IDC_B_SIMEND, &Csmart_parking_guiDlg::OnBnClickedBSimend)
ON_BN_CLICKED(IDC_B_SHOWSTATUS, &Csmart_parking_guiDlg::OnBnClickedBShowstatus)
END_MESSAGE_MAP()
// Csmart_parking_guiDlg message handlers
BOOL Csmart_parking_guiDlg::OnInitDialog()
{
CDialogEx::OnInitDialog();
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
// TODO: Add extra initialization here
return TRUE;
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
void Csmart_parking_guiDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialogEx::OnPaint();
}
}
// The system calls this function to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR Csmart_parking_guiDlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
void Csmart_parking_guiDlg::OnBnClickedBOpenConfig()
{
wchar_t szFilters[] = _T("Text Files (*.txt)|*.txt|All Files (*.*)|*.*||");
// Create an Open dialog
CFileDialog fileDlg(TRUE, _T("txt"), _T("*.txt"),
OFN_FILEMUSTEXIST | OFN_HIDEREADONLY, szFilters, this); // Display the file dialog.
// When user clicks OK, fileDlg.DoModal() returns IDOK.
if (fileDlg.DoModal() == IDOK)
{
CString m_strPathname = fileDlg.GetPathName();
CT2CA converter(m_strPathname);
std::string fileToOpen(converter);
// TODO: Open Grid file
open_file(*world, fileToOpen);
//Change the window's title to the opened file's title.
CString fileName = fileDlg.GetFileTitle();
SetWindowText(fileName);
}
}
void Csmart_parking_guiDlg::OnBnClickedBSaveconfig()
{
// TODO: Add your control notification handler code here
// szFilters is a text string that includes two file name filters:
// "*.my" for "MyType Files" and "*.*' for "All Files."
TCHAR szFilters[] = _T("Text Files (*.txt)|*.txt|All Files (*.*)|*.*||");
// Create a Save dialog
CFileDialog fileDlg(FALSE, _T("txt"), _T("*.txt"),
OFN_FILEMUSTEXIST | OFN_HIDEREADONLY, szFilters);
// Display the file dialog. When user clicks OK, fileDlg.DoModal()
// returns IDOK.
if (fileDlg.DoModal() == IDOK)
{
CString pathName = fileDlg.GetPathName();
CT2CA converter(pathName);
std::string fileToWrite(converter);
// Implement opening and reading file in here.
write_file(*world, fileToWrite);
//Change the window's title to the opened file's title.
CString fileName = fileDlg.GetFileTitle();
SetWindowText(fileName);
}
}
void Csmart_parking_guiDlg::OnBnClickedBNextevent()
{
// TODO: Add your control notification handler code here
run_simulation(*world);
m_GridSize = world->getGridSize(); // double
m_TimeDisplay = world->getTime(); // double
// THIS DOESN'T WORK
m_EchoSize.Format(_T("Grid size: %g"), m_GridSize);
m_EchoTime.Format(_T("Time: %g"), m_TimeDisplay);
UpdateData(FALSE);
GetDlgItem(IDC_ST_GRIDSIZE)->InvalidateRect(NULL);
GetDlgItem(IDC_ST_TIME)->InvalidateRect(NULL);
}
void Csmart_parking_guiDlg::OnBnClickedBSimend() // On clicking, simulation jumps to the very end.
{
jump_to_end(*world);
m_GridSize = world->getGridSize();
m_TimeDisplay = world->getTime();
// THIS DOESN'T WORK
m_EchoSize.Format(_T("Grid size: %g"), m_GridSize);
m_EchoTime.Format(_T("Time: %g"), m_TimeDisplay);
UpdateData(FALSE);
GetDlgItem(IDC_ST_GRIDSIZE)->InvalidateRect(NULL);
GetDlgItem(IDC_ST_TIME)->InvalidateRect(NULL);
}
void Csmart_parking_guiDlg::OnBnClickedBNewdest()
{
// TODO: Add your control notification handler code here
Cadd_Destination Dlg;
Dlg.DoModal();
}
void Csmart_parking_guiDlg::OnBnClickedBNewlot()
{
// TODO: Add your control notification handler code here
Cadd_Lot Dlg;
Dlg.DoModal();
}
void Csmart_parking_guiDlg::OnBnClickedBNewdriver() // Opens a dialog to input a new driver. Only works with added destination.
{
if (world->getDestinationCount() != 0) {
Cadd_Driver Dlg;
Dlg.DoModal();
}
}
void Csmart_parking_guiDlg::OnBnClickedBShowstatus()
{
// TODO: Add your control notification handler code here
}
Is there any way to fix this in order to make the values of the doubles show up in the GUI? I have tried the answer shown here
C++ MFC double to CString
but the numbers do not show up at all. There are no syntax errors. The code works if I use %d and replace the values with integers, but it doesn't work with double values, which is what I used in my initial classes.
I have fixed the problem myself.
As it turns out, the issue had more to do with my GUI. It turns out that the Static Text has a set length set in the Visual Studio Dialog Editor (accessed through the Resource View) and the length was too short to hold both the string containing "Grid size:" and the actual numbers. (The first Static Text initially could only hold one digit for both of them) I fixed it by extending the width of the Static Text in my GUI, and that fixed the problem.
As implied by the name, Static text controls are not expected to change once they are created. They don't automatically repaint when you change their content with SetWindowText, which is what DDX_Text calls to set the new text. You need to inform Windows that the contents have changed and the control needs repainting:
GetDlgItem(IDC_ST_GRIDSIZE)->InvalidateRect(NULL);
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.