Allowing IFileOpenDialog to pick a folder that doesn't exist yet - c++

I'm trying to create a dialog to select a new folder to save files into. The IFileOpenDialog class works great except that it won't allow a new folder to be picked.
I.e. "Folder: C:\existings\new-folder" in the bottom of the dialog pops up the following message:
new-folder
Path does not exist.
Check the path and try again.
Here's the code I've got:
IFileDialog* fileDialog
CoCreateInstance(CLSID_FileOpenDialog, NULL, CLSCTX_INPROC_SERVER,
IID_PPV_ARGS(&fileDialog));
DWORD options;
fileDialog->GetOptions(&options);
options &= ~FOS_FILEMUSTEXIST;
options &= ~FOS_PATHMUSTEXIST;
fileDialog->SetOptions(options | FOS_PICKFOLDERS);
fileDialog->Show(parentWindow);
Any pointers or hacks would be appreciated! Thanks!
To quote Michael from this other question:
[To head off some comments, the SHBrowseForFolder API still exists, but is still not an acceptable solution for our UI deciders.]
The same applies here...

I think you want to use CLSID_FileSaveDialog instead of CLSID_FileOpenDialog. And possibly make use of IFileSaveDialog in addition to the base class IFileDialog.

As you're selecting a folder, you could use the folder picker dialog.
This, with the right flags, has a "create" button at the bottom and a text entry allowing you to specifiy a non existant path.

Related

newbie: Code to show/hide a STATIC TEXT object in Visual C++ MFC app

I ran into a newbie problem with my first VC++ MFC app (actually, I ran into many problems, but RTFM and DuckDuckGo helped to solve them without crying here for help. Except this one!). Bear in mind that I am playing with this as a tutorial for myself, kind of a learn by example project, and I have a few years of Win GUI app programming experience in Deplhi/Lazarus, and now I am attempting to transition into VC++, simply for my own curiosity. While I am also good with C language programming, I have significantly less experience with C++. So the new programming environment and the less-known language together pose as my obstacle.
Here is what I did:
In a recently installed Visual Studio 2019 Community with only the Windows App development in C++ components selected, started a new project, chose C++ MFC App (Build apps with complex user interfaces that run on Windows.). Set application type to Dialog based, turn off all User Interface Features so only Thick frame is checked (unchecked System-menu, unchecked About-box), turn off all Advanced Features so only Common Control Manifest is checked (unck Printing and print preview, unck Activex controls, unck Support Restart Manager), clicked FINISH.
This prepared me an app with a single small main window, OK and Cancel buttons in its lower-right corner, and a STATIC TEXT item in the middle-center reading something like "TODO: add your own items here". Project name is TutMFC01p.
My goal was to hide that STATIC TEXT when I click one of the buttons, and make it visible again when I click the same button again.
It took me some time to realize that I should not fiddle with the OK and Cancel buttons to add them this functionality, and clicking either of these two buttons also quits my app (hence, no chance to click again). So I placed a new button on the dialog and worked with that instead. Clicking my button while my app was running did absolutely nothing - which was exactly what I wanted.
Double-clicking my button in the Dialog Editor dropped me into Source Editor with a new function autogenerated at the bottom of TutMFC01pDlg.cpp.
void CTutMFC01pDlg::OnBnClickedButton1()
{
// TODO: Add your control notification handler code here
}
Allrighty, so this is where I will add the code of what the button is supposed to do.
It also injected an ON_BN_CLICKED line to the MESSAGE MAP, which now looks like this.
BEGIN_MESSAGE_MAP(CTutMFC01pDlg, CDialogEx)
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDC_BUTTON1, &CTutMFC01pDlg::OnBnClickedButton1)
END_MESSAGE_MAP()
Allrighty again. So this is the way to tell the system that clicking my button should run the code given in CTutMFC01pDlg::OnBnClickedButton1().
The way I first tried to complete my goal was to alternate the STATIC TEXT object between the TRUE and FALSE value of the VISIBILE property upon the click of my button. A Delphi/Lazarus way of doing it is a single line of code like mainform.mystatictext.visible := not mainform.mystatictext.visible but I was not able to find a way to directly reference the property of an object and change its value with a simple assignment operation. What I found instead is that the way to hide objects is using the ShowWindow() method. I also run into difficulties trying to point this (or any other) method to the STATIC TEXT object, because apparently it has an ID of IDC_STATIC, which, apparently, cannot be referred to, as all static objects have this same ID. To simplify the task ahead, instead of hiding the STATIC TEXT I settled for hiding the button itself, and ended up with this code:
void CTutMFC01pDlg::OnBnClickedButton1()
{
// TODO: Add your control notification handler code here
CWnd* pMyButtonObj = GetDlgItem(IDC_BUTTON1);
pMyButtonObj->ShowWindow(SW_HIDE); //or SW_SHOW
}
This compiles and works very well. Obviously, once the button is pressed and disappears from the window, there is nothing to press again in order to unhide what was hidden. So I tried to move on from this already working code and modify it to act on the STATIC TEXT instead of the button itself. Logic suggested (my logic, anyways) that in order to gain the ability to refer to the ID of the STATIC TEXT, I need to assign a different ID to the STATIC TEXT. Something I can refer to. Something other than the not referrable IDC_STATIC. So I selected the STATIC TEXT object on the Dialog Editor, and in its Property palette I changed the value of the ID property from IDC_STATIC to IDC_STATIC1. This strangely has also changed the NAME property of the object to IDC_STATIC11. Earlier the NAME was IDC_STATIC1. Then in the code of OnBnClickedButton1() I replaced IDC_BUTTON1 with IDC_STATIC1, but that fails to compile complaining that there is no such object. Same happens when tried with IDC_STATIC11.
A little experimenting revealed another phenomena I am unable to explain (or understand). Similarly to how I changed the ID of STATIC TEXT, with my button selected in the Property Editor, I changed its ID from IDC_BUTTON1 to IDC_HideBtn. This also changed its NAME property.
Saved All, rebuilt project, and clicking my button still made it disappear, exactly as it was working before. HOWEVER, the source code of OnBnClickedButton1() and the MESSAGE MAP did not get updated to refer to the new ID, IDC_HideBtn, they still refer to IDC_BUTTON1, same as before.
void CTutMFC01pDlg::OnBnClickedButton1()
{
//TODO: Add your control notification handler code here
CWnd* pMyButtonObj = GetDlgItem(IDC_BUTTON1);
pMyButtonObj->ShowWindow(SW_HIDE);
}
But at this point, IDC_BUTTON1 should be a non-existing ID. Compile should fail. Yet it compiles fine, and it works fine.
QUESTIONS:
Why does the code compile and work with IDC_BUTTON1 in the source while the ID of the button is now IDC_HideBtn?
What can I do to be able to address the STATIC TEXT item as the argument to GetDlgItem() the same way as I could do with IDC_BUTTON1?
If STATIC TEXT items are not supposed to be programmatically changed then what other kind of item could I use instead? In Delphi/Lazarus there is a LABEL object similar to STATIC TEXT, but designed to get different Caption or other values many times while the program runs. In the toolbox of the Dialog Editor I see nothing like that, only STATIC TEXT. Or should I use an Input field instead, to display text in the dialog window?
Is there a way to implement the button click method in the way I initially tried to do the Delphi/Lazarus way? Changing the target object to visible from hidden, and to hidden from visible. Preferrably as a one-liner.
Is there NO WAY to directly refer to the property of an object and change its value with an assignment operation? Or only I did not find it how?
I have some small corrections (as I think), and I wanted to issue them as comments, but according to the comment policy it is better to post an answer despite that the answer has already been given.
Question 2:
It's strange that VS didn't add a new define for IDC_STATIC1 in resource.h on renaming a CStatic component (after all VS created a new id for a new button).
But of course, manual editing of resource.h is a very frequent procedure during programming with MFC, but it is necessary to update the _APS_NEXT_CONTROL_VALUE (and much less often _APS_NEXT_COMMAND_VALUE ) definition so that it points to a new correct value (not equal to previous definitions).
Question 3:
But you can write in you .rc file something like this:
BEGIN
DEFPUSHBUTTON "OK",IDOK,209,178,50,14
PUSHBUTTON "Cancel",IDCANCEL,263,178,50,14
CTEXT "TODO: Place dialog controls here.",IDC_MidTextObj,13,96,300,8
PUSHBUTTON "Hide object",IDC_HideBtn,135,106,50,14
END
and then in CTutMFC01pDlg.cpp:
void CTutMFC01pDlg::OnBnClickedHidebtn()
{
if (CWnd * pMyStaticObj = GetDlgItem(IDC_MidTextObj))
pMyStaticObj->ShowWindow(!pMyStaticObj->IsWindowVisible());
}
Question 4:
Also you can use the the DoDataExchange mechanism for getting/setting text for components like CStatic, CEdit, etc., and you can use ON_UPDATE_COMMAND_UI macros for enabling/disabling components.
But the basic way is to get a component as a CWnd class:
CWnd * pMyStaticObj = GetDlgItem(IDC_MidTextObj)
or get the component explicily:
CStatic* pMyStaticObj = static_cast<CStatic*>(GetDlgItem(IDC_STATIC1));
(don't use dynamic_cast here)
and then call methods of this fetched instance.
Thanks to the comments my question received, I could refine the direction of my web searches and also examine other files in my project folder to identify where trouble originates from, and understand how pieces of my MFC app fit together. Also, sometimes the inner workings of Visual Studio 2019 require a little manual editing help.
ANSWER 1)
All those IDC_xyzwq identifiers I can assign to the object in its property palette (values are selectable from a list) are predefined macros pointing to their respective numeric value. These live inside the resource.h file of the project. Unfortunately, VS2019 never allowed me to open this file as readable text - it always complained that the file is already open and asked me if I want to close it instead. To study the contents, I actually had to close my VS2019 solution, and open the resource.h file in a text editor. Here is what I found in there:
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by TutMFC01p.rc
//
#define IDD_TUTMFC01P_DIALOG 102
#define IDR_MAINFRAME 128
#define IDC_BUTTON1 1002
#define IDC_ButtHide 1002
#define IDC_HideBtn 1002
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 130
#define _APS_NEXT_COMMAND_VALUE 32771
#define _APS_NEXT_CONTROL_VALUE 1000
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
So it seems that each time I invented a new ID for my button and entered it in the Property Palette, VS2019 injected a new macro definition into the resource file, assigning it to the same numerical value of 1002. But other than auto-creating such entries, Visual Studio performs no maintenance on them and it is the responsibility of the programmer to keep order there. Which requires that the programmer understands what is what, and where it is stored in the project files.
So, even though my button object already had the ID value of IDC_HideBtn in its Property Palette, the earlier IDs of IDC_ButtHide and IDC_BUTTON1 were still valid and referred to the same numeric value of 1002, hence the source code using the old ID compiled, and the button worked fine.
Mind you, I also had to manually replace the button ID NAME to the chosen one in my apps MESSAGE MAP in TutMFC01pDlg.cpp before Visual Studio could reopen my solution/project. See the next section of my answer too.
ANSWER 2)
IDC_STATIC being a peculiar ID with some special treatment, I cannot just invent and type-in any new name into the ID property field of my STATIC TEXT item. More precisely, I actually CAN invent any new ID and enter that into the property field, but Visual Studio DOES NOT automatically generate the corresponding new macro definition in resources.h, most likely because it does not know what numeric value to assign to an object that is supposed to have no numeric value (as it was supposed to have the special value of -1). So instead of entering a new name in the ID property field, the programmer should close the solution, and manually edit the resources.h file in a text editor. YES, against all warning and discouragement in Microsoft Documentation and by seasoned developers, in this particular case it must be done manually. (Or at least, I do not know a better way than directly editing the resource file as text.) Here is what I changed my macro definitions to, by removing the two obsolete and unwanted button identifiers with the value of 1002, and manually adding a new definition entry intended for my STATIC TEXT item - with a numeric value that was not in use by any other entry. In my case, 1001 was not yet used, so that is what I assigned to my invented ID of IDC_MidTextObj.
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by TutMFC01p.rc
//
#define IDD_TUTMFC01P_DIALOG 102
#define IDR_MAINFRAME 128
#define IDC_HideBtn 1002
#define IDC_MidTextObj 1001
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 130
#define _APS_NEXT_COMMAND_VALUE 32771
#define _APS_NEXT_CONTROL_VALUE 1000
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
With these changes saved in resource.h I could close my Text Editor and reopen the solution/project in Visual Studio. Then I could select the STATIC TEXT item in the UI Editor, and in its Property Palette, in the field of the ID property, I could drop down the list of values and select my prepared value of IDC_MidTextObj. Mind you, there is another way to do this, by manually editing the .rc file of the Dialog. Which you will likely need to do for other reasons anyway. See next section of my answer.
ANSWER 3)
Here is the relevant part of my TutMFC01p.rc file.
IDD_TUTMFC01P_DIALOG DIALOGEX 0, 0, 320, 199
STYLE DS_SETFONT | DS_FIXEDSYS | WS_POPUP | WS_VISIBLE | WS_CAPTION | WS_THICKFRAME
EXSTYLE WS_EX_CLIENTEDGE | WS_EX_APPWINDOW
CAPTION "My VisualC++ Tutorial App 01"
FONT 8, "MS Shell Dlg", 0, 0, 0x1
BEGIN
DEFPUSHBUTTON "OK",IDOK,209,178,50,14
PUSHBUTTON "Cancel",IDCANCEL,263,178,50,14
CTEXT "TODO: Place dialog controls here.",IDC_STATIC,13,96,300,8
LTEXT "Hello MFC!",IDC_STATIC,22,33,86,8,WS_DISABLED
PUSHBUTTON "Hide object",IDC_HideBtn,135,106,50,14
END
I could just change the line starting with CTEXT and replace IDC_STATIC with IDC_MidTextObj to make sure that the STATIC TEXT item uses my pre-created value.
ALSO, if you look carefully, you see that the next line defines another STATIC TEXT item (a new static text item I added to the window in the Dialog Editor). But this is LTEXT instead of CTEXT. Without peeking at this code as text, I would not have known that there are these two different types. Maybe LTEXT is what I was after. I will see what I find about this in the documentation.
ANSWER 4)
Not as a one-liner. See also the next section of my answer for details. But it can be done with multiple lines of code, calling methods to first query the current state of visibility of the object, then hide it if it is visible, or show it if it is hidden.
ANSWER 5)
NO, there is no way to do that in VC++. It works in other languages, but in C++ you have to call functions/methods. See answer from Mark Ransom at the bottom of a similar issue.

Adding a non-button hyperlink to MFC application

I am trying to add a hyperlink that will direct a user of the application to a website. I see that MFC has a built in "MFC Link Control". In the dialog-editor. My hyperlinks look to work correctly.
When I debug my program, the links instead turn into buttons.
Is there a way to add non-button hyperlinks?
Thanks.
CButton is the natural base class of CMFCLinkCtrl. If it misses certain key properies, CMFCLinkCtrl will revert back to a CButton. My bet is on the URL. Try this:
CMFCLinkCtrl m_btnLink; // <-- associate with your control!
...
BOOL CTestDlg::OnInitDialog()
{
...
m_btnLink.SetURL(_T("http://www.example.com"));
m_btnLink.SetTooltip(_T("Link to my site"));
m_btnLink.SizeToContent();
...
}
Drag SysLink from Toolbox to your dialog box. Double click it and add this line to void function:
ShellExecute(
NULL, // or your can use GetSafeHwnd()
L"open",
L"http://stackoverflow.com/a/29181060/4057688",
NULL,
NULL,
SW_SHOWNORMAL
);
For more information visit.
Hope to be useful.

Problems with CMenu::ModifyMenu

I'm using CMenu::ModifyMenu in the OnCreate method of my CFrameWnd derived class to change the captions on my menu to match the user language.
I'm using VC++ designer and the menu is declared in a .rc file.
For the MENUITEM elements I use it as follow:
m_wndMenu->ModifyMenu(ID_APP_EXIT, MF_BYCOMMAND, NULL, CString((LPWSTR) ID_APP_EXIT));
For the POPUP elements (that don't have an ID) I use it as follow:
m_wndMenu->ModifyMenu(0, MF_BYPOSITION | MF_STRING, NULL, CString((LPWSTR) ID_MENU_POPUP_FILE));
It works as expected to change the captions, but for the menu items that are initialy disabled when I change the caption they get enabled. How do I fix this?
You may have to explicitly disable the menu item and set tool tip text after a call to ModifyMenu. Using ModifyMenu will effectively destroy the previous menu item and create a new one. You are losing any settings and initialization from the resource file or otherwise that you had on the previous item or menu.
See remarks: http://msdn.microsoft.com/en-us/library/4tbfebs6(v=vs.80).aspx
for such scenario, better to use EnableMenuItem function, like this
m_wndMenu->EnableMenuItem(ID_APP_EXIT, MF_BYCOMMAND| MF_ENABLED);
this will work...

Hardcoding the resources in application

I have some code which shows a simple dialog box and handles user action (written using plain WinAPI).
// Display dialog and handle user action
LRESULT choice = DialogBoxParam(NULL, MAKEINTRESOURCE(AP_IDD_DIALOG), NULL, (DLGPROC)DialogCallback, NULL);
Is there any way to hardcode the resource file dialog.rc, which is used to build the dialog ?(I would like to get rid of .rc files and I'm pretty sure there is a way, yet I don't know what it is :)
Edit
Also, does someone have any ideas on converting existing .rc files into hardcoded resources? Is this possible?
*.rc (resource) files are source code, they are compiled with the resource compiler and linked into your object (.exe/.dll)
You don't need to ship the resource file or have it present with your app to run it.
If you want to move to programmatically defined windows rather than templates then you might want to be looking at QT/wxWidgets. But thats a fair chunk of overhead for 1 dialog!
I'm surprised I couldn't find an existing app to do this sort of thing, enough hits on google with people trying to do this.
Ok, so the DLGTEMPLATE is a variable length blob of data, normally you let the dialog function pull it from the resource bundle for you, but instead you want to store it in your program.
You need to change your static lib to have a new function to decode some 'blob' back into the dlgtemplate, and you need to generate the blob. (or add the blob in your code without decoding which I don't want to think about right now)
The following code will give you the DLGTemplate data you need to imbed in your app. (cut from larger project)
HGLOBAL LoadResourceImpl(wchar_t *resource, wchar_t *type)
{
HRSRC handle = FindResource(hInstance, resource,type);
if (handle)
{
HGLOBAL hResource = LoadResource(hInstance, handle);
if (hResource)
return LockResource(hResource);
}
return 0;
}
DLGTEMPLATE * LoadDialog(wchar_t *resource)
{
return (DLGTEMPLATE *) LoadResourceImpl(resource,RT_DIALOG);
}
DLGTEMPLATE * LoadDialog(int resource)
{
return (DLGTEMPLATE *) LoadResourceImpl(MAKEINTRESOURCE(resource),RT_DIALOG);
}
Make an app that includes your resource - use the appropriate LoadDialog to get the data.
Now "write out" that blob in a format to include in your app -
step 1 - find out how much data there is by traversing the structure to find the total size including all the controls (control count is in DLGTEMPLATE::cdit)
step 2 - convert the data to something you can compile into your code - like HEX
Add to your static library a new 'HEX' to DLGTEMPLATE method and the hex string you made using the other app.
Can we hard code the .res file into the program?
the resource compiler converts .rc into .res
use a hex dump tool (eg. winhex) to translate the .res into bytes array
(represented in C source code).
add the source code file in the project and compile in the executable.
locate the dialog resource position from the array and use DialogBoxIndirect.
DialogBoxParamIndirect can be used instead. It takes as a parameter the dialog template. Raymond Chen's blog has an example of building a dialog box at runtime rather than from a resource using the DialogBox*Indirect API's.
Per MSDN, dialog box resources are basically composed of the DLGTEMPLATE and DLGITEMTEMPLATE structures. So you should be able to use the resource API's (FindResource, LoadResource, and LockResource) to get at the underlying bits of an existing dialog resource, and embed that within your code.
Note that this is a lot more painful than using the .rc file. It's much more difficult to make changes to your layout, and it's also much less localizable, since localization would now require a code change to update the template in code.
If it's a simple dialog, why use the DLGTEMPLATE at all?
Nothing stops you from simply doing ::CreateWindow'ing those controls directly. If it's a simple dialog with 2-3 buttons and a couple text fields, simply call ::CreateWindow, passing in the window class of whatever common control you're using.
This is essentially what the DialogXxxxx functions do anyway. DLGTEMPLATE is a convenience for declaratively laying out your forms, and having the boilerplate make the appropriate CreateWindow calls, etc.

How might I obtain the IContextMenu that is displayed in an IShellView context menu?

Building a file open dialog replacement. Much of it works now, but I would like to generate the view-mode drop-down for the toolbar directly from the shell view object.
Looking at IShellView2, I can see IShellView2::GetView() will give me the FOLDERVIEWMODE's supported. However, that doesn't give me the names of these modes, nor format that popup menu for me, nor immediately give me a way to actually set one of those modes (it would appear it is necessary to destroy the shell view window and create a replacement one for the current folder and specify the new FOLDERVIEWMODE desired... yeesh).
At any rate, if one right clicks on an IShellView window, one gets a context menu, the first submenu of which is exactly what I want to place in my drop-down toolbar button (ie. the "view" fly-out menu (e.g. Small Icons, Medium Icons, etc.)).
It seems like there ought to be a way to grab that submenu directly from the IShellView, rather than having to hardcode my values (and that way, if a given instance of IShellView supports extra view modes, they'd be there. Similarly, those which should be disabled would be, since it would all be under the IShellView's control).
I have read Raymond Chen's excellent How to host an IContextMenu. Unfortunately, that just gives me a very simplistic context menu - the one for the folder itself, or for a file in a given folder, but NOT the context menu for the IShellView's shell view window (from which I might obtain the view fly-out).
I have tried the following, based on Chen's article:
CComQIPtr<IContextMenu> pcm(m_shell_view); // <<-- FAIL resulting pointer is NULL <<<
// create a blank menu
CMenu menu;
if (!menu.CreatePopupMenu())
throw CContextException("Unable to create an empty menu in which to store the context menu: ");
// obtain the full popup menu we need
if (FAILED(m_hresult = pcm->QueryContextMenu(menu, 0, SCRATCH_QCM_FIRST, SCRATCH_QCM_LAST, CMF_NORMAL)))
throw CLabeledException("Unable to query the context menu for the current folder");
// display the menu to the user
// menu.getsubmenu
::TrackPopupMenu(menu, ::GetSystemMetrics(SM_MENUDROPALIGNMENT)|TPM_TOPALIGN|TPM_LEFTBUTTON, pt.x, pt.y, 0, m_shell_view_hwnd, NULL);
Unfortunately, the attempt to query the m_shell_view (which is an IShellView*) for its IContextMenu interface fails. This "works":
// retrieve our current folder's PIDL
PidlUtils::Pidl pidl(m_folder);
// get the context menu for the current folder
CComPtr<IContextMenu> pcm;
if (FAILED(m_hresult = GetUIObjectOf(m_owner->m_hWnd, pidl, IID_PPV_ARGS(&pcm))))
throw CLabeledException("Unable to obtain the PIDL for the current folder");
But here I get only a very few options in the context menu (Open, Explore, ...). Not the detailed context menu that I get if I simply right click on the shell view itself.
I'm out of ideas as to how to proceed. Help?! ;)
Try IShellView::GetItemObject with SVGIO_BACKGROUND as uItem to get a IContextMenu on the view object : http://msdn.microsoft.com/en-us/library/bb774832%28VS.85%29.aspx
There is the SHCreateDefaultContextMenu (Vista an up) that may be of help. Bjarke Viksoe website contains great info as well.
SVGIO_BACKGROUND will get you the background context menu of the shell view. You may need to call repeatedly pShellView->SelectItem for each PIDL you may have, then do the GetUIObjectOf call (then QI for IContextMenu, create a menu, call IContextMenu(3)::QueryContextMenu and finally display it with TrackPopupMenu).