MFC menu item checkbox behavior - visual-c++

I'm trying to add a menu item such that it acts like a check mark where the user can check/uncheck, and the other classes can see that menu item's check mark status. I received a suggestion of creating a class for the menu option (with a popup option), however, I can't create a class for the menu option when I'm in the resource layout editor in Visual Studio 2005. It would be great to hear suggestions on the easiest way to create menu items that can do what I have described.

You should use the CCmdUI::SetCheck function to add a checkbox to a menu item, via an ON_UPDATE_COMMAND_UI handler function, and the ON_COMMAND handler to change the state of the checkbox. This method works for both for your application's main menu and for any popup menus you might create.
Assuming you have an MDI or SDI MFC application, you should first decide where you want to add the handler functions, for example in the application, main frame, document, or view class. This depends on what the flag will be used for: if it controls application-wide behaviour, put it in the application class; if it controls view-specific behaviour, put it in your view class, etc.
(Also, I'd recommend leaving the menu item's Checked property in the resource editor set to False.)
Here's an example using a view class to control the checkbox state of the ID_MY_COMMAND menu item:
// MyView.h
class CMyView : public CView
{
private:
BOOL m_Flag;
afx_msg void OnMyCommand();
afx_msg void OnUpdateMyCommand(CCmdUI* pCmdUI);
DECLARE_MESSAGE_MAP()
};
// MyView.cpp
BEGIN_MESSAGE_MAP(CMyView, CView)
ON_COMMAND(ID_MY_COMMAND, OnMyCommand)
ON_UPDATE_COMMAND_UI(ID_MY_COMMAND, OnUpdateMyCommand)
END_MESSAGE_MAP()
void CMyView::OnMyCommand()
{
m_Flag = !m_Flag; // Toggle the flag
// Use the new flag value.
}
void CMyView::OnUpdateMyCommand(CCmdUI* pCmdUI)
{
pCmdUI->SetCheck(m_Flag);
}
You should ensure the m_Flag member variable is initialised, for example, in the CMyView constructor or OnInitialUpdate function.
I hope this helps!

#ChrisN's approach doesn't quite work for MFC Dialog applications (the pCmdUI->SetCheck(m_Flag); has no effect). Here is a solution for Dialog apps:
// MyView.h
class CMyView : public CView
{
private:
BOOL m_Flag;
CMenu * m_menu;
virtual BOOL OnInitDialog();
afx_msg void OnMyCommand();
DECLARE_MESSAGE_MAP()
};
// MyView.cpp
BEGIN_MESSAGE_MAP(CMyView, CView)
ON_COMMAND(ID_MY_COMMAND, OnMyCommand)
END_MESSAGE_MAP()
BOOL CMyView::OnInitDialog()
{
m_menu = GetMenu();
}
void CMyView::OnMyCommand()
{
m_Flag = !m_Flag; // Toggle the flag
if (m_flag) {
m_menu->CheckMenuItem(ID_MENUITEM, MF_CHECKED | MF_BYCOMMAND);
} else {
m_menu->CheckMenuItem(ID_MENUITEM, MF_UNCHECKED | MF_BYCOMMAND);
}
}
References:
http://www.codeguru.com/forum/showthread.php?t=322261

I ended up retrieving the menu from the mainframe using GetMenu() method, and then used that menu object and ID numbers to call CheckMenuItem() with the right flags, as well as GetMenuState() function.

Related

Change the navigation to come from bottom to top in MvvmCross in iOS + Xamarin

I am using MvvmCross and using ShowViewModel to navigate between view. It takes the default navigation behavior i.e., slides from Right->Left . I want few view controllers to slide from bottom to top . Can someone let me know how we can do this in MvvmCross. These are not overlays but regular view controllers.
You can achieve this by setting a custom delegate for your Navigation Controller. This can be done by override following method in your custom ViewPresenter
protected override void OnMasterNavigationControllerCreated()
{
this.MasterNavigationController.WeakDelegate = new NavigationControllerDelegate();
}
Within this delegate you can set your transitions, e.g.:
public class NavigationControllerDelegate : UINavigationControllerDelegate
{
public override IUIViewControllerAnimatedTransitioning GetAnimationControllerForOperation(UINavigationController navigationController, UINavigationControllerOperation operation, UIViewController fromViewController, UIViewController toViewController)
{
if (operation == UINavigationControllerOperation.Push)
{
if (fromViewController is MenuViewController)
{
return new BottomToTopTransition();
}
...
}
}
}
BottomToTopTransition is also a custom class and inherits from UIViewControllerAnimatedTransitioning. Last step is to override AnimateTransition() in this transition class and you are done.

Enable/Disable Edit box with help of Check-box control (MFC)

I have a checkbox and an edit control. I want to disable the Edit control when Check-box is 'not checked', and enable Edit control when Check-box is 'checked.
OnBnClickedCheck1 gets called when I check/uncheck the check-box. m_CHECK1_VARIABLE tells me if the check box is checked or un-checked. If-else part is executed correctly but m_TEXT1_CONTROL.EnableWindow(FALSE/TRUE) doesn't seem to work.
Below is the code.
void CPreparationDlg::OnBnClickedCheck1()
{
UpdateData(TRUE);
if (m_CHECK1_VARIABLE)
{
m_TEXT1_CONTROL.EnableWindow(TRUE);
}
else if (m_CHECK1_VARIABLE)
{
m_TEXT1_CONTROL.EnableWindow(FALSE);
}
}
There are 2 cases.
When Edit-box is disabled by default when dialog pops up.
If the Edit-box is enabled by default (I set 'Disabled' behavior in dialog properties to 'False'), Edit-box stays enabled throughout the operation. (check and uncheck operation on check-box)
When Edit-box is enabled by default when dialog pops up.
When I disable the Edit-box by default (I set 'Disabled' behavior in dialog properties to 'True'), Edit-box becomes enabled on 'first' 'check' on the Check-box but stays enabled throughout the rest of the operation. (check and uncheck operation on check-box).
What is it that I am missing here?
The following code example will implement the required logic.
Header file:
public:
int m_Check;
CEdit m_EditBox;
afx_msg void OnBnClickedCheck1();
Class implementation source:
CMfcApplicationDlg::CMfcApplicationDlg(CWnd* pParent /*=NULL*/)
: CDialog(CMfcApplicationDlg::IDD, pParent)
, m_Check(0) // Default checkbox state
{
// ...
}
void CMfcApplicationDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_EDIT1, m_EditBox);
DDX_Check(pDX, IDC_CHECK1, m_Check);
m_EditBox.EnableWindow(m_Check);
}
void CMfcApplicationDlg::OnBnClickedCheck1()
{
UpdateData();
}
All required functionality can be implemented inside the DoDataExchange() method. First time the edit box control state set according to the m_Check default value. And each next time the edit box control state will be triggered by OnBnClickedCheck1() event.
IMHO using DoDataExchange(..) to maintain the state of a dialog is dicey at best. Add a member like UdateState( ) and use that. Stage the dialog in OnInitDialog( ) with anything that doesn't easily initialize in the constructor and call UpdateState( ).
Use DoDataExchange(..) only to do what it sounds like, exchange data between the dialog and objects. This way you won't paint yourself into a corner as the Dialog evolves.
//....h
CEdit m_EditBox;
CButton m_CheckBox;
//...cpp
BOOL MyDialog::OnInitDialog( )
{
if( ! CDialogEx::OnInitDialog( ) )
return FALSE;
//do more stuff then
UpdateState( );
return TRUE;
}
void MyDialog::UpdateState( )
{
m_EditBox.EnableWindow( m_CheckBox.GetCheck( ) == BST_CHECKED );
//more state stuff...
}
void MyDialog::OnBnClickedCheck1( )
{
UpdateState( );
}

Remove button bar from jface dialog

I would like to create a dialog without the OK/Cancel buttons. I know that if you override the createButton method, this can be achieved.
What do you think of overriding the createButtonBar method to return null if the button bar is not required at all? This would save some code.
Overriding createButtonBar is going to produce errors if you return null for the result composite as the Dialog code expects it to not be null.
You can override createButtonsForButtonBar and not create any buttons. It looks like Dialog always checks that individual buttons exist.
You can remove the space used by the buttons composite like this:
#Override
protected void createButtonsForButtonBar(final Composite parent)
{
GridLayout layout = (GridLayout)parent.getLayout();
layout.marginHeight = 0;
}
If you want to have the only one "Close" button on your dialog, you can do it so:
#Override
public void create() {
super.create();
getButton(IDialogConstants.OK_ID).setVisible(false);
getButton(IDialogConstants.CANCEL_ID).setText("Close");
}

Supporting two storyboards

I have an app with a medium-sized storyboard, which is complicated enough for me not to want to mess around with it too much.
I want to copy this storyboard and change the color scheme and let the user select which color scheme to use.
My question is: can I programmatically select which storyboard will be used by default on startup? If yes - how do I do that?
I looked at a somewhat related question: Storyboards Orientation Support in Xcode 4.5 and iOS 6.x ?
Based on that code I made an extension method:
static bool IsStoryboardLoading {get;set;}
public static T ConsiderSwitchingStoryboard<T> (this UIViewController from) where T: UIViewController
{
if (!IsStoryboardLoading && LocalStorage.Instance.IsWhiteScheme && false) {
try {
IsStoryboardLoading = true;
UIStoryboard storyboard = UIStoryboard.FromName ("MainStoryboard_WHITE", NSBundle.MainBundle);
T whiteView = storyboard.InstantiateViewController (typeof(T).Name) as T;
from.PresentViewController (whiteView, false, null);
return whiteView;
} finally {
IsStoryboardLoading = false;
}
}
return null;
}
}
and then I use it in ViewDidAppear override:
public override void ViewDidAppear (bool animated)
{
this.ConsiderSwitchingStoryboard<MyViewController> ();
}
This code works in some cases but in others it causes an error when performing a push segue:
NSGenericException Reason: Could not find a navigation controller for segue 'segSearchResults'. Push segues can only be used when the source controller is managed by an instance of UINavigationController.
at (wrapper managed-to-native) MonoTouch.ObjCRuntime.Messaging:void_objc_msgSendSuper_IntPtr_IntPtr (intptr,intptr,intptr,intptr)
It might be simpler to just use 1 Storyboard and have 2 sets of controllers in the same storyboard. Just use different storyboard ids for the controllers. You can use the same class on those if needed.
For example:
var whiteController = Storyboard.InstantiateViewController("MyWhiteController") as MyController;
var blueController = Storyboard.InstantiateViewController("MyBlueController") as MyController;
Both could create an instance of MyController, but pull out different layouts from the same storyboard file.
Another option is to use UIAppearance to dynamically set a "style" on all controls of a certain type in your app.
For example, to set the default UIBarButtonItem image throughout your app:
UIBarButtonItem.Appearance.SetBackgroundImage(UIImage.FromFile("yourpng.png"), UIControlState.Normal, UIBarMetrics.Detault);
(You might check my parameters there)

Visual C++ - MFC how to change disablity of a button using edit box

I'm currently working with MFC, and I want to make a simple account managment.
I made a login button which is set to disabled from the start and 2 edit box which each one of them is a user id and a password.
I want to make a simple thing : if one of the edit box has no value at all then make the loggin button disabled, else..make the button available.
However, the code doesn't work at all.
this is the code :
part of the header file
// 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:
// Value of the "Username" textbox
CString m_CStr_UserID;
// Control variable of the "Username" textbox
CEdit m_CEdit_ID;
// Value of the "Password" textbox
CString m_CStr_UserPass;
// Control variable of the "Password" textbox
CEdit m_CEdit_PASS;
// Control variable of the "Login" button
CButton m_Btn_Login;
public:
afx_msg void OnEnChangeEditId();
afx_msg void OnEnChangeEditPass();
proceed to the .cpp
.....
void CTestDlg::OnEnChangeEditId()
{
// TODO: If this is a RICHEDIT control, the control will not
// send this notification unless you override the CDialog::OnInitDialog()
// function and call CRichEditCtrl().SetEventMask()
// with the ENM_CHANGE flag ORed into the mask.
// TODO: Add your control notification handler code here
m_CEdit_ID.GetWindowTextW(m_CStr_UserID);
if(!m_CStr_UserID.IsEmpty() && !m_CStr_UserPass.IsEmpty())
m_Btn_Login.EnableWindow(TRUE);
m_Btn_Login.EnableWindow(FALSE);
}
void CTestDlg::OnEnChangeEditPass()
{
// TODO: If this is a RICHEDIT control, the control will not
// send this notification unless you override the CDialog::OnInitDialog()
// function and call CRichEditCtrl().SetEventMask()
// with the ENM_CHANGE flag ORed into the mask.
// TODO: Add your control notification handler code here
m_CEdit_PASS.GetWindowTextW(m_CStr_UserPass);
if(!m_CStr_UserPass.IsEmpty() && !m_CStr_UserID.IsEmpty())
m_Btn_Login.EnableWindow(TRUE);
m_Btn_Login.EnableWindow(FALSE);
}
What's wrong with the code?
In both handlers it's always being enabled FALSE. I think you're missing an else
You either need to return after the EnableWindow(TRUE) or use an else.
acraig5057 explained the problem with your code and showed you how to work around it. I will just add that you can also do this: map the EN_CHANGE for both edit controls to one handler, let's call it OnEnChangeEditIdOrPass:
void CTestDlg::OnEnChangeEditIdOrPass()
{
m_Btn_Login.EnableWindow((m_CEdit_ID.GetWindowTextLength() != 0) &&
(m_CEdit_PASS.GetWindowTextLength() != 0));
}
The function GetWindowTextLength returns the number of characters in the specified edit control and 0 if the edit control is empty.
The logic of the above code is this: if both the edit boxes have characters in them, the && will return TRUE and the login button will be enabled. If at least one of them does not, the && will return FALSE and the login button will be disabled.
Of course, this code not save the values of the username and the password edit controls into string variables, like your code does, but you can always call GetWindowText from inside the handler of the login button.

Resources