I have learned C/C++ Basics and practiced , but I have hard time understanding
Microsoft documentation and find it confusing Documention example
for example : I try to create command line program that should let the user open
folder dialog and choose folder , as result the folders path should be stored in variable
did research and found that there is many ways to achieve this goal but the best way is using IFileDialog::GetFolder method (shobjidl_core.h)
what the difference between file dialogs?
The main question :
How to get folders path as string variable based on user choice from file dialog?
There is c++ resources with practical tutorials ?
I try to understand how I use the following dialog :
Folder dialog
it refernces me to:
BROWSEINFOA structure
Would be very helpful if someone could explain how I can use this folder dialog or something better
any great tutorial of windows/linux file system handling
I used to wcout to print out path
TCHAR path[260];
BROWSEINFO bi = { 0 };
LPITEMIDLIST pidl = SHBrowseForFolder(&bi);
SHGetPathFromIDList(pidl, path);
wcout << path << '\n';
We can use com interface as well :
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE, PWSTR pCmdLine, int nCmdShow);
{
HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
if (SUCCEEDED(hr))
{
IFileOpenDialog* pFileOpen;
// Create the FileOpenDialog object.
hr = CoCreateInstance(CLSID_FileOpenDialog, NULL, CLSCTX_ALL,IID_IFileOpenDialog, reinterpret_cast<void**>(&pFileOpen));
// if object created ( that's com object )
if (SUCCEEDED(hr))
{
// Show the Open dialog box.
hr = pFileOpen->Show(NULL);
// Get the file name from the dialog box.
if (SUCCEEDED(hr))
{
IShellItem* pItem;
hr = pFileOpen->GetResult(&pItem);
if (SUCCEEDED(hr))
{
PWSTR pszFilePath;
hr = pItem->GetDisplayName(SIGDN_FILESYSPATH, &pszFilePath);
// Display the file name to the user.
if (SUCCEEDED(hr))
{
MessageBoxW(NULL, pszFilePath, L"File Path", MB_OK);
CoTaskMemFree(pszFilePath);
cout << pszFilePath;
std::string stringtoconvert;
std::wstring temp = std::wstring(stringtoconvert.begin(), stringtoconvert.end());
LPCWSTR lpcwstr = temp.c_str();
}
pItem->Release();
}
}
pFileOpen->Release();
}
CoUninitialize();
}
return 0;
}
Important to mention :
Open and Save As common dialog boxes ( commdlg.h ) have been superseded by the Common Item Dialog
For linux and other platforms there is cross platforms libraries like Qt and more , here is a link for UI solutions
and about Microsoft documentation : I think there should be simpler examples and explanations its complicated & frustrating to learn this way.
Related
When I create a common file dialog on Windows, I can add application specific shortcuts on the left pane with IFileDialog::AddPlace.
The shortcuts are all displayed in a virtual folder called "Application Links". But when I click on "Application Links" the folder seems to be empty showing only "No items match your search.":
Is it possible to display all the shortcuts listed at "Application Links" on the left pane, also in the right pane when I click on "Application Links" itself? And if so, how can I accomplish that?
Here is a minimal working example of the code producing the screenshot above:
#include <windows.h>
#include <shobjidl.h>
int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
{
HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
if (SUCCEEDED(hr)) {
IFileDialog *pfd = NULL;
hr = CoCreateInstance(CLSID_FileOpenDialog, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pfd));
if (SUCCEEDED(hr)) {
IShellItem *psiShortcut;
// Get ShellItem for "C:\Windows\System32"
hr = SHCreateItemFromParsingName(L"C:\\Windows\\System32", 0, IID_IShellItem, (void**) &psiShortcut);
if (SUCCEEDED(hr)) {
// Add the ShellItem for "C:\Windows\System32" to the file dialogs shortcut list
hr = pfd->AddPlace(psiShortcut, FDAP_BOTTOM);
if (SUCCEEDED(hr)) {
// Open file dialog and show result in a message box on OK
hr = pfd->Show(NULL);
if (SUCCEEDED(hr) && hr != HRESULT_FROM_WIN32(ERROR_CANCELLED)) {
IShellItem *psiFileName;
hr = pfd->GetResult( &psiFileName);
if (SUCCEEDED(hr)) {
PWSTR pwszFileName;
hr = psiFileName->GetDisplayName(SIGDN_FILESYSPATH, &pwszFileName);
if (SUCCEEDED(hr)) {
MessageBoxW(NULL, pwszFileName, L"Note", MB_OK);
CoTaskMemFree( pwszFileName );
}
psiFileName->Release();
}
}
}
psiShortcut->Release();
}
pfd->Release();
}
CoUninitialize();
}
return 0;
}
I have seen this in many applications. You get the option to open a file and if it does not exists, it is created and you don't get any complain. All from the same Open File dialog.
I use IFileOpenDialog to open a file and if I input a file that does not exists, it shows me an error and I cannot get the path to this file.
What I want is not to get an error but have the non existing file name accepted. Later I will create it. Is this possible?
if (SUCCEEDED(hr))
{
IFileOpenDialog *pFileOpen;
// Create the FileOpenDialog object
hr = CoCreateInstance(
CLSID_FileOpenDialog,
NULL,
CLSCTX_ALL,
IID_IFileOpenDialog,
reinterpret_cast<void**>(&pFileOpen)
);
if (SUCCEEDED(hr))
{
// Show the Open dialog box.
hr = pFileOpen->Show(NULL);
// Get the file name from the dialog box.
if (SUCCEEDED(hr))
{
IShellItem *pItem;
hr = pFileOpen->GetResult(&pItem);
if (SUCCEEDED(hr))
{
PWSTR pszFilePath;
hr = pItem->GetDisplayName(SIGDN_FILESYSPATH, &pszFilePath);
// Check if file actually exists
if (SUCCEEDED(hr))
{
// Create file if not found
if (PathFileExists(pszFilePath) != 1)
{
}
CoTaskMemFree(pszFilePath);
}
pItem->Release();
}
}
pFileOpen->Release();
}
CoUninitialize();
}
call IFileDialog::GetOptions to get the default options, remove FOS_PATHMUSTEXIST and FOS_FILEMUSTEXIST bits, then set the new options back with IFileDialog::SetOptions.
[Revised yet again for clarity]
I have a C++ program which interacts with a website. The site is IE-specific, and so is my program.
I'm connecting to the running instance of IE in an ordinary way (out of process -- see code). Once I get the IWebBrowser2, I have no problem getting the IHTMLDocument2 and interacting with the individual IHTMLElement objects, filling in fields and clicking buttons.
But if the web page has javascript that calls window.showModalDialog, I'm stuck: I need to interact with the HTML elements in the popup, just like the other pages; but I can't seem to get its IWebBrowser2.
The popup is always titled "Web Page Dialog", and is a window of type Internet Explorer_TridentDlgFrame containing an Internet Explorer_Server. But I can't get the IWebBrowser2 from the Internet Explorer_Server window the way I can when it's a normal IE instance.
I can get the IHTMLDocument2Ptr, but when I try to get the IWebBrowser2 I get an HRESULT of E_NOINTERFACE.
The code is pretty standard stuff, and works fine if it's a 'normal' IE window
IHTMLDocument2Ptr pDoc;
LRESULT lRes;
/* hWndChild is an instance of class "Internet Explorer_Server" */
UINT nMsg = ::RegisterWindowMessage( "WM_HTML_GETOBJECT" );
::SendMessageTimeout( hWndChild, nMsg, 0L, 0L, SMTO_ABORTIFHUNG, 1000,
(DWORD*)&lRes );
LPFNOBJECTFROMLRESULT pfObjectFromLresult =
(LPFNOBJECTFROMLRESULT)::GetProcAddress( hInst, "ObjectFromLresult" );
if ( pfObjectFromLresult != NULL )
{
HRESULT hr;
hr = (*pfObjectFromLresult)( lRes, IID_IHTMLDocument, 0, (void**)&pDoc );
if ( SUCCEEDED(hr) ) {
IServiceProvider *pService;
hr = pDoc->QueryInterface(IID_IServiceProvider, (void **) &pService);
if ( SUCCEEDED(hr) )
{
hr = pService->QueryService(SID_SWebBrowserApp,
IID_IWebBrowser2, (void **) &pBrowser);
// This is where the problem occurs:
// hr == E_NOINTERFACE
}
}
}
In case it matters, this is Vista and IE8. (I emphasize this because both of these introduced breaking changes in my codebase, which had worked fine with XP/IE7.)
Once again, my goal is to get each IHTMLElement and interact with it. I don't have access to the source code of the application which I'm automating.
I'm considering sending keystrokes blindly to the Internet Explorer_Server window, but would rather not.
Edited to add:
Someone suggested getting the child windows and sending them messages, but I'm pretty sure that doesn't work with Internet Explorer_Server; according to Spy++, there's aren't any child windows. (This is not IE-specific. Java applets don't seem to have child windows, either.)
Update
In the comments, Simon Maurer said the above code worked for him, and just to make sure there were no typos he very generously posted a complete standalone app on pastebin. When I used his code, it failed in the same way in the same place, and I realized he thought I wanted to connect to the underlying page, not the popup. So I've edited the text above to remove that ambiguity.
I don't know why you want to get the IServiceProvider or IWebBrowser2 if you just want the IHTMLElement's. You can get them by calling the IHTMLDocument's get_all() method.
This code snippet shows you how this works:
#include <Windows.h>
#include <mshtml.h>
#include <Exdisp.h>
#include <atlbase.h>
#include <SHLGUID.h>
#include <oleacc.h>
#include <comdef.h>
#include <tchar.h>
HRESULT EnumElements(HINSTANCE hOleAccInst, HWND child)
{
HRESULT hr;
UINT nMsg = ::RegisterWindowMessage(_T("WM_HTML_GETOBJECT"));
LRESULT lRes = 0;
::SendMessageTimeout(child, nMsg, 0L, 0L, SMTO_ABORTIFHUNG, 1000, (PDWORD)&lRes);
LPFNOBJECTFROMLRESULT pfObjectFromLresult = (LPFNOBJECTFROMLRESULT)::GetProcAddress(hOleAccInst, "ObjectFromLresult");
if (pfObjectFromLresult == NULL)
return S_FALSE;
CComPtr<IHTMLDocument2> spDoc;
hr = (*pfObjectFromLresult)(lRes, IID_IHTMLDocument2, 0, (void**)&spDoc);
if (FAILED(hr)) return hr;
CComPtr<IHTMLElementCollection> spElementCollection;
hr = spDoc->get_all(&spElementCollection);
if (FAILED(hr)) return hr;
CComBSTR url;
spDoc->get_URL(&url);
printf("URL: %ws\n", url);
long lElementCount;
hr = spElementCollection->get_length(&lElementCount);
if (FAILED(hr)) return hr;
printf("Number of elements: %d", lElementCount);
VARIANT vIndex; vIndex.vt = VT_I4;
VARIANT vSubIndex; vSubIndex.vt = VT_I4; vSubIndex.lVal = 0;
for (vIndex.lVal = 0; vIndex.lVal < lElementCount; vIndex.lVal++)
{
CComPtr<IDispatch> spDispatchElement;
if (FAILED(spElementCollection->item(vIndex, vSubIndex, &spDispatchElement)))
continue;
CComPtr<IHTMLElement> spElement;
if (FAILED(spDispatchElement->QueryInterface(IID_IHTMLElement, (void**)&spElement)))
continue;
CComBSTR tagName;
if (SUCCEEDED(spElement->get_tagName(&tagName)))
{
printf("%ws\n", tagName);
}
}
return S_OK;
}
int _tmain(int argc, _TCHAR* argv[])
{
::CoInitialize(NULL);
HINSTANCE hInst = ::LoadLibrary(_T("OLEACC.DLL"));
if (hInst != NULL)
{
HRESULT hr = EnumElements(hInst, (HWND)0x000F05E4); // Handle to Internet Explorer_Server determined with Spy++ :)
::FreeLibrary(hInst);
}
::CoUninitialize();
return 0;
}
Above code works on both: a normal window or a modal window, just pass the correct HWND to the SendMessageTimeout function.
WARNING I use a hard-coded HWND value in this example, if you want to test it you should start an IE instance and get the HWND of the Internet Explorer_Server window using Spy++.
I also advise you to use CComPtr to avoid memory leaks.
I’m stuck with an issue and I’m pretty sure that this forum will be able to help me for this.
I’m trying to add few automation objects to the scripts (hosted via a separate process (ATL EXE server)).
Also I am trying to sink the events from these automation objects inside my ATL EXE script engine.
To achive this I’m using CDispExSinkConnector as described in http://www.codeproject.com/Articles/3326/Extending-the-Internet-Explorer-Scripting-Engine
As described I’m using IDispatchEx::GetDispID()to create new members inside the scripting engine. Once the member DISPID has been created, I’m using InvokeEx()to set the property value.
But these method calls return RPC_E_SYS_CALL_FAILED.
Note- Here I get the IDispEx pointer from an OUT-OF-PROC IDispatch pointer.
More detailed descriptions:
I do have a BrowserCtrl hosted by CAxWindow in an ATL EXE server which I’m using to create HTML plug-ins for my MFC client application.
The ATL EXE server provides wrapper methods to IWebBrowser2 methods so that I can call methods like IWebBrowser2Ptr->Navigate2().
Also I can subscribe to IWebBrowser2 events like OnDocumentComplete(….)in this ATL EXE server and ultimately forward those to my MFC Client application to handle those there.
Below are few code snippets for my ATL EXE server (BrowserCtrl):
1st is CreateControl() which creates the CAxWindow, creates the WebBrowser Control and host the control on internal default CAxHostWindow.
STDMETHODIMP BrowserCtrl::CreateControl(ULONG hwndParent, LONG left,LONG top, LONG right, LONG bottom)
{
CRect rc(left, top, right, bottom);
// Create the AX host window. m_wndBrowserCtrl is CAxWindow object
HWND hwndAxHost = m_wndBrowserCtrl.Create(reinterpret_cast<HWND>(hwndParent), &rc, L"Shell.Explorer", WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN | WS_CLIPSIBLINGS, 0, ID_BROWSERCTRL );
//Obtain a pointer to the container object
CComQIPtr<IAxWinHostWindow> ptrWinHost;
HRESULT hr = m_wndBrowserCtrl.QueryHost(&ptrWinHost);
LPOLESTR lpszCLSID = NULL;
hr = StringFromCLSID(CLSID_WebBrowser, &lpszCLSID);
// Create the WebBrowser Ctrl
CComPtr<IUnknown> cpIUnknown = NULL;
hr = ptrWinHost->CreateControlEx(lpszCLSID, m_wndBrowserCtrl, NULL, &cpIUnknown, __uuidof(SHDocVw::DWebBrowserEvents2), reinterpret_cast<IUnknown*>(reinterpret_cast<DWebBrowserEvents2Impl*>(this)));
// Get the IWebBrowser2 interface pointer for the control
// CComQIPtr<IWebBrowser2> m_cpIBrowser;
m_cpIBrowser = cpIUnknown;
return S_OK;
}
//Now the wrapper method for IWebBrowser2 methods
STDMETHODIMP BrowserCtrl::Navigate2(VARIANT *pwszUrl, VARIANT *Flags, VARIANT *TargetFrameName, VARIANT *PostData, VARIANT *Headers)
{
HRESULT hr = m_cpIBrowser->Navigate2(pwszUrl, Flags,TargetFrameName,PostData,Headers);
}
//Now the event handlers for the IWebBrowser2 events:
void __stdcall BrowserCtrl::OnDocumentComplete(IDispatch* pDisp, VARIANT* pvaURL)
{
Fire_OnDocumentComplete(pDisp , pvaURL);// forwarding to the MGC client APP
}
Now the issue:
1.On the MFC Client APP and in the event handler function OnDocumentComplete() I do the following:
void MFCClientApp::HandleDocumentComplete(LPDISPATCH pIDisp, VARIANT* pvaURL)
{
CComPtr<IDispatch> pDispDoc;
CComQIPtr<IDispatch> pScriptDisp;
CComQIPtr<IDispatchEx> pDispEx;
CComQIPtr<IHTMLDocument> pHTMLDoc;
CComQIPtr<IWebBrowser2> pWebBrowser;
if (pIDisp != NULL)
{
pWebBrowser = pIDisp;
//CComPtr<IDispatch> ptrIDisp;
//BOOL bResult = GetOPBrowser()->GetDisp(&ptrIDisp);
//pWebBrowser = ptrIDisp;
pWebBrowser->get_Document(&pDispDoc);
if (pDispDoc != NULL)
{
// Get the IDispatchEx interface
pHTMLDoc = pDispDoc;
if (pHTMLDoc != NULL)
{
pHTMLDoc->get_Script(&pScriptDisp);
pDispEx = pScriptDisp;
if (pDispEx != NULL)
{
CDispExSinkConnector pDispExSinkConnector = new CDispExSinkConnector();
Hr = pDispExSinkConnector->SetDispEx(pDispEx); // here the Hr returned is 0x80010100 “System Call Failed” i.e. RPC_E_SYS_CALL_FAILED
……
……..
………
}
Here is the SetDispEx() and internal related functions:
void CDispExSinkConnector::SetDispEx(IDispatchEx *pDispEx)
{
CComBSTR bstrThisGuid("AC0B188C-6B55-408f-9E8C-821B9B5467CB"); // #!I8NIGNORE
HRESULT hr = m_pDispExGIT.Attach(pDispEx);//add it to the GIT Table
ASSERT(pDispEx);
// We need to add ourselves to the script engine
AddNamedObject(bstrThisGuid, this);
}
HRESULT CDispExSinkConnector::AddNamedObject(BSTR bsName, IDispatch *pDisp)
{
HRESULT hr = 0;
CComPtr<IDispatchEx> pDispEx;
GetDispEx(&pDispEx);
if(pDispEx == NULL)
return E_FAIL;
if(!bsName || SysStringLen(bsName) == 0 || !pDisp)
return E_INVALIDARG;
// Also, add our root objects into the script namespace
DISPID dispIdThis = 0;
hr = pDispEx->GetDispID(bsName, fdexNameEnsure | fdexNameCaseSensitive,&dispIdThis); // here the Hr returned is 0x80010100 “System Call Failed” i.e. RPC_E_SYS_CALL_FAILED
if (hr == DISP_E_UNKNOWNNAME)
…
..
}
Please help me to find out the root cause and a solution to resolve this issue.
Your quick help will be much appreciated.
Thanks,
SP
The example program provided here to run a video file. I am using "avi" format file for playing with DShow APIs in Visual Studio 2015.
Refer to the complete code:
#include<dshow.h>
#include<iostream>
using namespace std;
int CALLBACK WinMain(
_In_ HINSTANCE hInstance,
_In_ HINSTANCE hPrevInstance,
_In_ LPSTR lpCmdLine,
_In_ int nCmdShow
)
{
IGraphBuilder *pGraph = NULL;
IMediaControl *pControl = NULL;
IMediaEvent *pEvent = NULL;
HRESULT hr = CoInitialize(NULL);
if (FAILED(hr))
{
cout << "ERROR - Could not initialize COM library"<<endl;
return -1;
}
hr = CoCreateInstance(CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER, IID_IGraphBuilder, (void **)&pGraph);
if (FAILED(hr))
{
cout << "EROR - Could not create the Filter Graph Manager";
return -1 ;
}
hr = pGraph->QueryInterface(IID_IMediaControl, (void **)&pControl);
hr = pGraph->QueryInterface(IID_IMediaEvent, (void**)&pEvent);
hr = pGraph->RenderFile(L"C:\\Users\\sunil\\Documents\\Ramp\\output.avi", NULL);
if (SUCCEEDED(hr))
{
hr = pControl->Run();
if (SUCCEEDED(hr))
{
long evCode;
pEvent->WaitForCompletion(INFINITE, &evCode);
}
}
pControl->Release();
pEvent->Release();
pGraph->Release();
CoUninitialize();
return 0;
}
The build is successful but when I run it a windows pops up with the title "ActiveMovie window".
But there is no video in the window.
I referred to the comments on the same page and many others faced the same issue. However a few were able to successfully run the program.
What is it that I am doing wrong?
My question is taken from another similar question. I could not comment in that question coz I am new to Stack Overflow.
The code is about right (plays for me just as is). Typical problems with the code include:
there is a codec issue, you are trying to play a file with specific encoding, which is not picked up or handling is overridden by another third party software (which might be okay on its own but creates a problem together with #2 below).
you are ignoring the fact that WaitForCompletion call is blocking execution on the thread and you are in the same time responsible for dispatching window messages there because you initialized COM as STA.
An easy way to find out if #2 is the problem is placing MessageBox call between Run and WaitForCompletion. MessageBox dispatches messages for you and as long as you keep the box open, video plays as well (or start playing well and keeps playing even after you close the box). Proper solution is to wait and displach messages in the same time (WaitDispatchingMessages, this SO question or similar).