What is the "Shell Namespace" way to create a new folder? - c++

Obviously this is trivial to do with win32 api - CreateDirectory(). But I'm trying to host an IShellView, and would like to do this the most shell-oriented way. I would have thought that there would be a createobject or createfolder or some such from an IShellFolder. But neither IShellView nor IShellFolder nor even IFolderView seem to have anything quite like this.
Is there a Shell-programming way to create a new folder? Or do I need to create a folder using a pathname, the old-fashioned way?
If I have to do it via CreateDirectory(), then my next question might be: any ideas as to how to get the IShellView / IFolderView to actually see this new object and display it to the user?
Motivation: Creating my own File Dialog replacement and I want to provide the "new folder" toolbar icon functionality of the standard XP-style file dialog.
EDIT: I went ahead and created something that basically works, using CreateDirectory. However, I'm still hoping that there's a better way to do this, but so that you can see how that works, and to offer better ideas as to solve this issue better:
PidlUtils::Pidl pidl(m_folder);
CFilename folderName(GetDisplayNameOf(pidl), "New Folder");
for (int i = 2; folderName.Exists(); ++i)
folderName.SetFullName(FString("New Folder (%d)", i));
if (!CPathname::Create(folderName, false))
throw CContextException("Unable to create a new folder here: ");
// get the PIDL for the newly created folder
PidlUtils::Pidl pidlNew;
#ifdef UNICODE
const wchar_t * wszName = folderName.c_str();
#else
wchar_t wszName[MAX_PATH];
MultiByteToWideChar(CP_ACP, 0, folderName.GetFullName(), -1, wszName, MAX_PATH);
#endif
m_hresult = m_folder->ParseDisplayName(NULL, NULL, wszName, NULL, pidlNew, NULL);
if (FAILED(m_hresult))
throw CLabeledException(FString("Unable to get the PIDL for the new folder: 0x%X", m_hresult));
// upgrade our interface so we can select & rename it
CComQIPtr<IShellView2> sv2(m_shell_view);
if (!sv2)
throw CLabeledException("Unable to obtain the IShellView2 we need to rename the newly created folder.");
// force it to see thew new folder
sv2->Refresh();
// select the new folder, and begin the rename process
m_hresult = sv2->SelectAndPositionItem(pidlNew, SVSI_EDIT|SVSI_DESELECTOTHERS|SVSI_ENSUREVISIBLE|SVSI_POSITIONITEM, NULL);
if (FAILED(m_hresult))
throw CLabeledException(FString("Unable to select and position the new folder item: 0x%X", m_hresult));

Yes, you can get IContextMenu and look for sub menus, but why bother, just call SHChangeNotify after you call CreateDirectory

Shell folders usually implement the IStorage interface, so this is pretty simple. For example, the following creates a folder named "abcd" on the desktop:
CComPtr<IShellFolder> pDesktop;
HRESULT hr = SHGetDesktopFolder(&pDesktop);
if (FAILED(hr)) return;
CComQIPtr<IStorage> pStorage(pDesktop);
if (!pStorage) return;
CComPtr<IStorage> dummy;
hr = pStorage->CreateStorage(L"abcd", STGM_FAILIFTHERE, 0, 0, &dummy);

The Win32 API function CreateDirectory seems to be the "correct way". At least, I can find nothing better - and the answers here don't really shed any light on a better way to do it.

Related

Is there a way to get IShellBrowser from a dialog?

I know that windows common dialog have a IShellBrowser interface and its class name is 'SHELLDLL_DefView'. Refer this.
How to get the IShellBrowser interface of a file open dialog?
(The file open dialog is outside's, not my application's.)
This is the same as my question but is delphi(?) ver.
I don't know delphi code. How to solve this problem as C++ or MFC code?
Here is a C/C++ translation of the Delphi code:
const UINT CWM_GETISHELLBROWSER = WM_USER + 7;
IShellBrowser *ShellBrowser = (IShellBrowser*) SendMessage(aDialog, CWM_GETISHELLBROWSER, 0, 0);
if (ShellBrowser) {
ShellBrowser->AddRef();
// use ShellBrowser as needed...
ShellBrowser->Release();
}
You might also want to read the following article, which provides a slightly more official (ie, more reliable, but more complicated) way to get an IShellBrowser for a given HWND:
Querying information from an Explorer window
Start with the ShellWindows object which represents all the open shell windows. You can enumerate through them all with the Item property... From each item, we can ask it for its window handle and see if it's the one we want... Okay, now that we have found the folder via its IWebBrowserApp, we need to get to the top shell browser. This is done by querying for the SID_STopLevelBrowser service and asking for the IShellBrowser interface.

How can I add text to the file I create using IFileOperation?

I looked at the MSDN samples for IFileOperation, and they show how to create a file, but I don't want to create a blank file, I want to add some text in it. Here's what I have from the sample:
IFileOperation *pfo;
HRESULT hr = CreateAndInitializeFileOperation(IID_PPV_ARGS(&pfo));
if (SUCCEEDED(hr))
{
hr = pfo->NewItem(psiFolder, FILE_ATTRIBUTE_NORMAL, c_szFileName, NULL, NULL);
if (SUCCEEDED(hr))
{
hr = pfo->PerformOperations();
}
pfo->Release();
}
In the pfo->NewItem call, the fourth parameter is for the template, but I don't want to define a template.I want to create a .Url file with the content:
[InternetShortcut]
URL=www.google.com
I can't even seem to control the format of the file, let alone the content. Please help!
IFileOperation::NewItem lets you access the functionality of the 'ShellNew' menu (the menu you get if you right-click in a folder, and select New from the context menu). It's designed to let you make a folder or an empty file, or create a new file from a pre-existing template. It doesn't let you make a file containing arbitrary data.
Once you've created a new empty file you could open it using CreateFile() and write your data to it using WriteFile(). But note that CreateFile() could create the file for you as well - there's really no need to use IFileOperation simply to create an empty file (unless you need its support for UAC to create the file in a protected location, but in that case you'll have trouble writing to it afterwards).

Create DataObject from Shell Run / Help (MFC C++)

I need help to create an IDataObject to enable drag and drop of these 2 Items (Run and Help)
For Example I need to do just like Windows Startmenu does.
to run them I use these
CComPtr<IShellDispatch2> pShellDisp;
if (SUCCEEDED(CoCreateInstance(CLSID_Shell,NULL,CLSCTX_SERVER,IID_IShellDispatch2,(void**)&pShellDisp)))
{
pShellDisp->Help(); //Help
pShellDisp->FileRun(); //Run
}
Can you guys help me out ?
PS: I need the drag with image Icons too
EDIT [SOLVED]
IShellFolder* desk = NULL;
HRESULT hr =SHGetDesktopFolder(&desk);
LPITEMIDLIST pidl2=NULL;
ULONG cbEaten;
DWORD dwAttribs = 0 ;
hr = desk->ParseDisplayName(NULL,
NULL,
L"shell:::{2559a1f3-21d7-11d4-bdaf-00c04f60b9f0}",
&cbEaten, // This can be NULL
&pidl2,
&dwAttribs);
hr = desk->GetUIObjectOf(parentHwnd, 1,
(PCITEMID_CHILD*)&pidl2, IID_IDataObject, 0, (LPVOID *)lpdataObj);
desk->Release();
return;
for run:
shell:::{2559a1f3-21d7-11d4-bdaf-00c04f60b9f0}
I assume you only want one of those items in the data object at any point in time, in that case:
If you already have a IShellItem then you can call IShellItem::BindToHandler(...,BHID_DataObject,...).
If you only have the pidl you can use SHCreateDataObject or CIDLData_CreateFromIDArray
If you want to drag&drop both items in the same operation then things get hard. I don't know if both of those objects have the same parent. If they do then even the old CIDLData_CreateFromIDArray can handle it. If they don't then you could try SHCreateShellItemArrayFromIDLists and then use IShellItemArray::BindToHandler(...,BHID_DataObject,...). To support < Vista I believe you have to create your own CFSTR_SHELLIDLIST and add it to the dataobject.
Drag images are not really related to this and should be asked in a separate question where you include information about your IDragSourceHelper etc.

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

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.

IWebBrowser2: how to force links to open in new window?

The MSDN documentation on WebBrowser Customization explains how to prevent new windows from being opened and how to cancel navigation. In my case, my application is hosting an IWebBrowser2 but I don't want the user to navigate to new pages within my app. Instead, I'd like to open all links in a new IE window. The desired behavior is: user clicks a link, and a new window opens with that URL.
A similar question was asked and answered here and rather than pollute that answered post, it was suggested I open a new discussion.
The members on the related post suggested I should be able to do this by trapping DISPID_BEFORENAVIGATE2, setting the cancel flag, and writing code to open a new window, but I've found out that the browser control gets lots of BeforeNavigate2 events that seem to be initiated by scripts on the main page. For example, amazon.com fires BeforeNavigate2 events like crazy, and they are not a result of link invocation.
Replies appreciated!
What I ended up doing was using IHTMLDocument directly rather than IWebBrowser. IWebBrowser is a superset of IHTMLDocument, and the navigation model implemented by IWebBrowser isn't customizable to the degree I wanted.
I actually got MS Developer Support involved and this approach was their recommendation. They say this is what Outlook uses for HTML-based email, which is the user experience I wanted to emulate. They also confirmed that there's no reliable way to filter the OnBeforeNavigate events that result from user action from those that result from script activity.
Hope this helps anybody facing the same issues. It wasn't too hard to port the code to use IHTMLDocument. If you end up doing this, you may also find yourself looking for a way to figure out when the document is done loading. To do that, hook HTMLDocumentEvents instead of DWebBrowserEvents, and look for the DISPID_HTMLDOCUMENTEVENTS_ONREADYSTATECHANGE event. It doesn't tell you what the ready state is; you need to call IHTMLDocument::get_readyState and parse the resulting string. Goofy, but there you go.
You can bind to onclick event before document is complete while creating browser in OnCreate() using IHTMLDocument2::put_onclick():
#include <comutil.h>
ClickEvents<RootFrame> clickEvents;
_variant_t clickDispatch;
clickDispatch.vt = VT_DISPATCH;
clickDispatch.pdispVal = &clickEvents;
CComQIPtr<IDispatch> dispatch;
hr = webBrowser2->get_Document(&dispatch);
ASSERT_EXIT(SUCCEEDED(hr), "webBrowser->get_Document(&dispatch)");
CComQIPtr<IHTMLDocument2> htmlDocument2;
hr = dispatch->QueryInterface(IID_IHTMLDocument2, (void**) &htmlDocument2);
ASSERT_EXIT(SUCCEEDED(hr), "dispatch->QueryInterface(&htmlDocument2)");
htmlDocument2->put_onclick(clickDispatch);
ClickEvents class implements IDispatch, you only need to implement Invoke method, in rest return E_NOTIMPL:
HRESULT STDMETHODCALLTYPE Invoke(DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags,
DISPPARAMS *pDispParams, VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr)
{
HRESULT hr;
CComQIPtr<IWebBrowser2> webBrowser2;
hr = rootFrame->GetDlgControl(rootFrame->rootview.GetDlgCtrlID(), IID_IWebBrowser2, (void**) &webBrowser2);
ASSERT_EXIT(SUCCEEDED(hr), "rootframe->GetDlgControl(IID_IWebBrowser2) failed");
CComQIPtr<IDispatch> dispatch;
hr = webBrowser2->get_Document(&dispatch);
ASSERT_EXIT(SUCCEEDED(hr), "webBrowser2->get_Document(&dispatch)");
CComQIPtr<IHTMLDocument2> htmlDocument2;
hr = dispatch->QueryInterface(IID_IHTMLDocument2, (void**) &htmlDocument2);
ASSERT_EXIT(SUCCEEDED(hr), "dispatch->QueryInterface(&htmlDocument2)");
CComQIPtr<IHTMLWindow2> htmlWindow2;
hr = htmlDocument2->get_parentWindow((IHTMLWindow2**) &htmlWindow2);
ASSERT_EXIT(SUCCEEDED(hr), "htmlDocument2->get_parentWindow(&htmlWindow2)");
CComQIPtr<IHTMLEventObj> htmlEvent;
hr = htmlWindow2->get_event(&htmlEvent);
ASSERT_EXIT(SUCCEEDED(hr), "htmlWindow2->get_event(&htmlEvent)");
CComQIPtr<IHTMLElement> htmlElement;
hr = htmlEvent->get_srcElement(&htmlElement);
ASSERT_EXIT(SUCCEEDED(hr), "htmlEvent->get_srcElement(&htmlElement)");
CComBSTR hrefAttr(L"href");
VARIANT attrValue;
VariantInit(&attrValue);
hr = htmlElement->getAttribute(hrefAttr, 0 | 2, &attrValue); // 0 = case insensitive, 2 = return BSTR
ASSERT_EXIT(SUCCEEDED(hr), "htmlElement->getAttribute()");
wchar_t href[2084]; // maximum url length in IE, http://support.microsoft.com/kb/208427
wcsncpy_s(href, _countof(href), attrValue.bstrVal, _TRUNCATE);
if (!rootFrame->IsURLAllowed(href)) {
VARIANT variant;
variant.vt = VT_BOOL;
variant.boolVal = VARIANT_FALSE;
htmlEvent->put_returnValue(variant);
ShellExecute(0, L"open", href, 0, 0, SW_SHOWNORMAL);
}
return S_OK;
}
As you can see after querying some interfaces I finally have the element that got clicked, then I call IsURLAllowed() defined in my root frame to check whether to allow opening url in current webbrowser window or whether to open it using default browser on user's computer.
This handles all links even if they were appended to document using javascript.
The same should be done with "onsubmit" events for forms.
I also think I have a solution for "window.location" redirects in javascript, I haven't tested it yet, but I will soon test it and I will update this answer then. You could use a combination of "onunload" and "onbeforeunload" events along with DWebBrowserEvents2::BeforeNavigate2(), after onunload/onbeforeunload are called you will know that user is leaving current page so now in BeforeNavigate2() you can cancel it. You can attach unload events using IHTMLWindow2::put_onunload() and IHTMLWindow2::put_onbeforeunload().
See sources of a complete solution for the "onclick" below.
AttachClickEvents in BrowserFrame:
http://code.google.com/p/phpdesktop/source/browse/phpdesktop-msie/msie/browser_frame.h?r=709d00b991b5#125
Invoke in ClickEvents(IDispatch):
http://code.google.com/p/phpdesktop/source/browse/phpdesktop-msie/msie/click_events.h?r=a5b0b350c933#132
I'm hypothesising here but yet another approach could be to maintain a count of navigation events, incrementing the counter on DISPID_BEFORENAVIGATE2 and decrementing it on occurrences of DISPID_NAVIGATECOMPLETE2 and DISPID_NAVIGATEERROR. With that in place, you could speculate that whenever you get DISPID_BEFORENAVIGATE2 and your counter is at zero, it is actual user navigation / link invocation.
I have no idea whether this approach would work, or whether those are the right events you'd need to make it work, but it could be worth investigating.
You could try a different approach instead and physically add the attribute target="_blank"
to all <a> tags in the rendered document.
This approach would involve waiting for DISPID_DOCUMENTCOMPLETE and then using IHTMLDocument3::getElementsByTagName() to fetch all of the anchor elements. You would then use IHTMLElement::setAttribute() to set target="_blank" on each of them.
It seems to me, that it you want "to open all links in a new IE window", it means that you want that the opening of new windows must be done in another process. The easiest way to do so: using CreateObject("InternetExplorer.Application") way (see another question which solve a problem, which is opposite to your question: InternetExplorer.Application object and cookie container). With this way you will receive the best isolation from your application and the user who clicks on the link receive all possibilities which exist in IE. You should of cause continue usage of BeforeNavigate2 events to find out the moment when "a new IE window" should be opened.