The code below for file with no-extension brings up a dialog shown below listing applications that can be used to open the file. This behavior is seen only from Windows-8. And the applications listed in the dialog are taken from HKEY_LOCAL_MACHINE\SOFTWARE\Classes*\OpenWithList. Is there anyway to suppress this dialog and get a behavior similar to old platforms?
-Karthik
SHELLEXECUTEINFO shinfo;
unsigned long mask = SEE_MASK_FLAG_NO_UI;
memset(&shinfo,0,sizeof(shinfo));
shinfo.cbSize = sizeof(shinfo);
shinfo.fMask = SEE_MASK_FLAG_DDEWAIT | mask;
shinfo.hwnd = NULL;
shinfo.lpVerb = "open";
shinfo.lpFile = prog;
shinfo.lpParameters = NULL;
shinfo.lpDirectory = 0;
shinfo.fMask = SEE_MASK_FLAG_NO_UI;
shinfo.nShow = SW_SHOWDEFAULT;
rc = ShellExecuteEx(&shinfo);
I'd suspect there is no default action associated with open on Windows 8 for files without an extension. I confirmed this using your code (a Delphi version of it, anyway) on Windows 7.
Running the code with shinfo.lpverb set to 'open' caused ShellExecuteEx to return FALSE, and GetLastError did indeed return ERROR_NO_ASSOCIATION. However, changing lpVerb to NULL (nil in Delphi) instead displayed the standard Win7 Open With dialog, just like your code does on Windows 8.
Here's a modified version of your code for testing:
SHELLEXECUTEINFO shinfo;
memset(&shinfo, 0, sizeof(shinfo));
shinfo.cbSize = sizeof(shinfo);
shinfo.fMask = SEE_MASK_FLAG_DDEWAIT | SEE_MASK_FLAG_NO_UI;
shinfo.lpVerb = NULL;
shinfo.lpFile = prog;
shinfo.hwnd = NULL;
shinfo.lpParameters = NULL;
shinfo.lpDirectory = 0;
shinfo.nShow = SW_SHOWDEFAULT;
rc = ShellExecuteEx(&shinfo);
Here's my test Delphi code for comparison (a quite literal translation of your C++ code):
var
shInfo: TShellExecuteInfo;
FillChar(shInfo, SizeOf(shInfo), 0); // Same result as memset()
shInfo.cbSize := SizeOf(shInfo);
shInfo.fMask := SEE_MASK_FLAG_NO_UI or SEE_MASK_FLAG_DDEWAIT;
shInfo.Wnd := 0;
shInfo.lpVerb := nil; // Also tested with 'open'
shInfo.lpDirectory := 'D:\TempFiles'; // Path to my no-extension file
shInfo.lpFile := 'datafile'; // My test file with no ext
shInfo.nShow := SW_SHOWDEFAULT;
if not ShellExecuteEx(#shInfo) then
ShowMessage(SysErrorMessage(GetLastError)); // Readable error message
A quick change to your code to replace "open" with NULL as the lpVerb should confirm.
You can also confirm my suspicion fairly easily by right-clicking a file with no extension in Win8's Explorer, and checking the bold default action at the top of the context menu. If there is no bold option, or if it's anything but open, my suspicions are correct.
Related
I need to start a process and have access to the PID, so I am trying to use ShellExecuteEx. I am attempting to open a batch file. However, no matter how I pass the parameters and no matter where the file is located and what permission's I have on the file, the function is returning with Error Code 5: Access is denied.
The File is located in the same location as the config files that have already been read successfully.
The File is set for full access permissions with any user.
It does this with any file type. I've tried just opening text files with the same outcome (Error 5)
If I use ShellExecute() instead, the batch file is run successfully.
Here is some of the code I've tried:
SHELLEXECUTEINFO exInfo;
exInfo.cbSize = sizeof(SHELLEXECUTEINFO);
exInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
exInfo.lpVerb = "open";
exInfo.lpFile = "C:\\batchtest.bat";
exInfo.nShow = SW_NORMAL;
BOOL hReturnCode = ShellExecute(&exInfo);
DWORD LastError = GetLastError();
I've also tried:
SHELLEXECUTEINFO exInfo;
exInfo.cbSize = sizeof(SHELLEXECUTEINFO);
exInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
exInfo.lpVerb = "open";
exInfo.lpFile = "C:\\Windows\\system32\\cmd.exe";
exInfo.lpParameters = "batchtest.bat";
And many variations of the above.
Also, I've tried something really simple like from here:
Get PID from ShellExecute
to no avail.
However this:
ShellExecute(NULL, "open", "C:\\testbat.bat", NULL, NULL, SW_SHOWNORMAL);
works without an error. Unfortunately, I need the PID, so I can't use ShellExecute.
Any suggestions would be greatly appreciated. I feel like I've exhausted all of my options.
Environment:
VS 2008
Windows 7
EDIT: fixed the code to "C:\batchtest.bat"; as suggested. (Still same result)
Figured it out.
In order to run batch file and I guess some other types of exe's on Windows 7, you have to elevate the call using the lpVerb = _TEXT("runas") -- even if you have UAC turned off. This isn't documented in the SHELLEXECUTEINFO structure documentation on MDSN (it isn't even given as an option), since it says: "The following verbs are commonly used"
The final code was as follows:
SHELLEXECUTEINFO exInfo;
exInfo.cbSize = sizeof(SHELLEXECUTEINFO);
exInfo.fMask = SEE_MASK_NOCLOSEPROCESS; //allows the PID to be returned
exInfo.hwnd = NULL;
exInfo.lpVerb = _TEXT("runas"); //elevates for Windows 7
exInfo.lpFile = "C:\\BatchTest.bat";
exInfo.lpParameters = NULL;
exInfo.nShow = SW_MAXIMIZE;
exInfo.hInstApp = NULL;
exInfo.lpDirectory = NULL;
BOOL hReturnCode = ShellExecuteEx(&exInfo);
I hope that helps others out.
Shouldn't the line
exInfo.lpFile = "C:\\batchtest.exe";
be
exInfo.lpFile = "C:\\batchtest.bat";
I have a VS2010 C++ application that uses the Windows Common File Dialog in a pretty ordinary fashion. My company just updated my workstation to a nice quad core CPU with Windows 7 whereas my previous system was still running XP. When I run my application inside the Visual Studio debugger, any attempt to call the CFD seems to fail silently with the code throwing no apparant errors to the output window, and no dialog appearing. Outside the debugger things work just fine. I invoke the dialog pretty much the same way every time.
CString theFilterList = "CSV Import Files (*.csv)|*.csv";
theFilterList = theFilterList + "|All files (*.*)|*.*||";
// construct the common dialog
CFileDialog fileDlg(TRUE, NULL, NULL,OFN_ENABLESIZING | OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST | OFN_HIDEREADONLY | OFN_ALLOWMULTISELECT, theFilterList,this);
POSITION pos;
// Initialize m_ofn structure
fileDlg.m_ofn.lpstrTitle = "Please select a UP supplied CSV file to prepare to load into SCT.";
// Create buffer for file names.
const DWORD bufferSize = (MAX_MULTISELECT_FILENAMES * MAX_FILENAMESIZE) + 1;
TCHAR* filenamesBuffer = new TCHAR[bufferSize];
// Initialize beginning and end of buffer.
filenamesBuffer[0] = NULL;
filenamesBuffer[bufferSize-1] = NULL;
// Attach buffer to OPENFILENAME member.
fileDlg.m_ofn.lpstrFile = filenamesBuffer;
fileDlg.m_ofn.nMaxFile = bufferSize;
if ( fileDlg.DoModal() != IDOK)
{
theCSVFilenameList.RemoveAll();
return;
}
pos = fileDlg.GetStartPosition();
while( pos )
{
theCSVFilenameList.Add(fileDlg.GetNextPathName( pos ));
}
I just had this problem. I found that my StackReserve size was too high. I reduced it and the dialog started coming up. Though in my case it was happening both in and out of the debugger.
The Win32 function GetKeyNameText will provide the name of keyboard keys in the current input locale.
From MSDN:
The key name is translated according to the layout of the currently
installed keyboard, thus the function may give different results for
different input locales.
Is it possible to force the input locale for a short amount of time? Or is there another alternative to GetKeyNameText that will always return the name in English?
Update: This answer does not work. It actually modifies the keyboard settings of the user. This appear to be a behavior change between Windows versions.
CString csLangId;
csLangId.Format( L"%08X", MAKELANGID( LANG_INVARIANT, SUBLANG_NEUTRAL ) );
HKL hLocale = LoadKeyboardLayout( (LPCTSTR)csLangId, KLF_ACTIVATE );
HKL hPrevious = ActivateKeyboardLayout( hLocale, KLF_SETFORPROCESS );
// Call GetKeyNameText
ActivateKeyboardLayout( hPrevious, KLF_SETFORPROCESS );
UnloadKeyboardLayout( hLocale );
WARNING: GetKeyNameText is broken (it returns wrong A-Z key names for non-english keyboard layouts since it uses MapVirtualKey with MAPVK_VK_TO_CHAR that is broken), keyboard layout dlls pKeyNames and pKeyNamesExt text is bugged and outdated. I cannot recommend dealing with this stuff at all. :)
If you're really-really want to get this info - then you can load and parse it manually from keyboard layout dll file (kbdus.dll, kbdger.dll etc).
There is a bunch of undocumented stuff involved:
In order to get proper keyboard layout dll file name first you need to convert HKL to KLID string. You can do this via such code:
// Returns KLID string of size KL_NAMELENGTH
// Same as GetKeyboardLayoutName but for any HKL
// https://docs.microsoft.com/en-us/windows-hardware/manufacture/desktop/windows-language-pack-default-values
BOOL GetKLIDFromHKL(HKL hkl, _Out_writes_(KL_NAMELENGTH) LPWSTR pwszKLID)
{
bool succeded = false;
if ((HIWORD(hkl) & 0xf000) == 0xf000) // deviceId contains layoutId
{
WORD layoutId = HIWORD(hkl) & 0x0fff;
HKEY key;
CHECK_EQ(::RegOpenKeyW(HKEY_LOCAL_MACHINE, L"SYSTEM\\CurrentControlSet\\Control\\Keyboard Layouts", &key), ERROR_SUCCESS);
DWORD index = 0;
while (::RegEnumKeyW(key, index, pwszKLID, KL_NAMELENGTH) == ERROR_SUCCESS)
{
WCHAR layoutIdBuffer[MAX_PATH] = {};
DWORD layoutIdBufferSize = sizeof(layoutIdBuffer);
if (::RegGetValueW(key, pwszKLID, L"Layout Id", RRF_RT_REG_SZ, nullptr, layoutIdBuffer, &layoutIdBufferSize) == ERROR_SUCCESS)
{
if (layoutId == std::stoul(layoutIdBuffer, nullptr, 16))
{
succeded = true;
DBGPRINT("Found KLID 0x%ls by layoutId=0x%04x", pwszKLID, layoutId);
break;
}
}
++index;
}
CHECK_EQ(::RegCloseKey(key), ERROR_SUCCESS);
}
else
{
WORD langId = LOWORD(hkl);
// deviceId overrides langId if set
if (HIWORD(hkl) != 0)
langId = HIWORD(hkl);
std::swprintf(pwszKLID, KL_NAMELENGTH, L"%08X", langId);
succeded = true;
DBGPRINT("Found KLID 0x%ls by langId=0x%04x", pwszKLID, langId);
}
return succeded;
}
Then with KLID string you need to go to HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Keyboard Layouts\%KLID% registry path and read Layout File string from it.
Load this dll file from SHGetKnownFolderPath(FOLDERID_System, ...) (usually C:\Windows\System32) with LoadLibrary() call.
Next you need to do GetProcAddress(KbdDllHandle, "KbdLayerDescriptor") - you're receive pointer that can be casted to PKBDTABLES.
There is kbd.h header in Windows SDK that have KBDTABLES struct definition (there is some stuff involved to use proper KBD_LONG_POINTER size for x32 code running on x64 Windows. See my link to Gtk source at the end).
You have to look at pKeyNames and pKeyNamesExt in it to get scan code -> key name mapping.
Long story short: The GTK toolkit have the code that doing all this(see here and here). Actually they are building scan code -> printed chars tables from Windows keyboard layout dlls.
I have the following code, I use to Open a File Open Dialog using Win32 API. It works fine in 32bit, but fails when I use in a 64bit (In a DLL). What am I doing wrong?
char Filestring[256];
Filter = "OBJ files\0*.obj\0\0";
char* returnstring = NULL;
OPENFILENAME opf;
opf.hwndOwner = mainHWND;
opf.lpstrFilter = Filter;
opf.lpstrCustomFilter = 0;
opf.nMaxCustFilter = 0L;
opf.nFilterIndex = 1L;
opf.lpstrFile = Filestring;
opf.lpstrFile[0] = '\0';
opf.nMaxFile = 256;
opf.lpstrFileTitle = 0;
opf.nMaxFileTitle=50;
opf.lpstrInitialDir = Path;
opf.lpstrTitle = "Open Obj File";
opf.nFileOffset = 0;
opf.nFileExtension = 0;
opf.lpstrDefExt = "*.*";
opf.lpfnHook = NULL;
opf.lCustData = 0;
opf.Flags = (OFN_PATHMUSTEXIST | OFN_OVERWRITEPROMPT) & ~OFN_ALLOWMULTISELECT;
opf.lStructSize = sizeof(OPENFILENAME);
if(GetOpenFileName(&opf))
{
returnstring = opf.lpstrFile;
if (returnstring) {
result = returnstring;
}
}
EDIT: By failing, I meant that the Open File Dialog doesn't show up. The code still returns zero without any errors.
EDIT 2: I have called CommDlgExtendedError() and it returned 1. From the MSDN reference, does it mean the dialog has invalid lStructSize? I have checked the sizeof(OPENFILENAME) and it returned 140 bytes.
UPDATE: In my Project Settings, Under Code Generation the "Struct Member Alignment" is set to 4 Bytes(/Zp4). I changed this to default and it magically worked. Look for the answers and their comments below for more information.
You aren't initialising lpTemplateName and so it contains random stack noise. This in turn will lead to 'hInstance` being references which also contains stack noise.
When calling a function like this you should first of all zero out the struct and only fill in the fields that are non-zero. Something like this:
OPENFILENAME opf={0};
opf.lStructSize = sizeof(OPENFILENAME);
opf.hwndOwner = mainHWND;
opf.lpstrFilter = Filter;
opf.nFilterIndex = 1L;
opf.lpstrFile = Filestring;
opf.lpstrFile[0] = '\0';
opf.nMaxFile = 256;
opf.lpstrInitialDir = Path;
opf.lpstrTitle = "Open Obj File";
opf.lpstrDefExt = "*.*";
opf.Flags = OFN_PATHMUSTEXIST | OFN_OVERWRITEPROMPT;
There was no need to exclude OFN_ALLOWMULTISELECT explicitly since you were not including it in the first place!
EDIT
You state in a comment that this doesn't work. Calling CommDlgExtendedError is a good idea and should tell you why it fails.
You could also try to run the minimal possible GetOpenFileName which is this:
char Filestring[MAX_PATH] = "\0";
OPENFILENAME opf={0};
opf.lStructSize = sizeof(OPENFILENAME);
opf.lpstrFile = Filestring;
opf.nMaxFile = MAX_PATH;
GetOpenFileName(&opf);
I have the very same problem and a partial solution :
+ the simple following simple example (proposed abobe) was not working in x64 mode.
+ I changed the complie option "struct Member Alignment" from 1byte /Zp1 to default which solved this problem (by introducing others !!!)
char Filestring[MAX_PATH] = "\0";
OPENFILENAME opf={0};
opf.lStructSize = sizeof(OPENFILENAME);
opf.lpstrFile = Filestring;
opf.nMaxFile = MAX_PATH;
GetOpenFileName(&opf);
To find out more you should call CommDlgExtendedError to get the error code what went wrong. Besides this I would initialize all member of the struct to 0 with
ZeroMemory(&opf, sizeof(opf));
Since the file open dialog is in reality a COM component it could be worth to check out if your thread apartment state is different under 64 bit.
if( RPC_E_CHANGED_MODE == CoInitialize(NULL) )
ASSERT(FALSE); // MTA Apartment found
CoUnitialize()
Yours,
Alois Kraus
As a note in Microsoft Office 2010 64-bit we gave up and used the internal wrappers as the structure turned into 140 bytes and we were not sure how to change alignment.
Application.GetOpenFilename(FileFilter, FilterIndex, Title, ButtonText, MultiSelect)
and Application.GetSaveAsFilename(InitialFilename, FileFilter, FilterIndex, Title, ButtonText)
http://msdn.microsoft.com/en-us/library/ff834966.aspx
http://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel._application.getopenfilename.aspx
Needless to say we think all individuals with fairly heavy applications in Excel should start considering other options as maintaining future versions across multiple clients and platforms may just be... insane!
I managed to get around this problem by setting the packing appropriately before including the header file. That way, for the purpose of this one function, we were using the 'default' 16 byte alignment, but did not have to change the packing alignment for the rest of our program:
#ifdef _WIN64
#pragma pack( push )
#pragma pack( 16 )
#include "Commdlg.h"
#pragma pack( pop )
#else
#include "Commdlg.h"
#endif // _WIN64
As in title, is there any Win32 API to do that?
Don't do this.
I'm 99% sure there isn't an official API for it, for exactly the same reason that there wasn't programmatic access to the old Start Menu's pin list.
In short, most users don't want programs putting junk in their favorites, quick launch, taskbar, etc. so Windows doesn't support you doing as such.
I'm trying to implement a VirtuaWin (opensource virtual desktop software) plugin that allows me to pin different buttons to different virtual desktops. Completely valid reason to use this.
Found the way to pin/unpin it already:
Following code snippet is taken from Chromium shortcut.cc file, nearly unchanged, see also the ShellExecute function at the MSDN
bool TaskbarPinShortcutLink(const wchar_t* shortcut) {
int result = reinterpret_cast<int>(ShellExecute(NULL, L"taskbarpin", shortcut,
NULL, NULL, 0));
return result > 32;
}
bool TaskbarUnpinShortcutLink(const wchar_t* shortcut) {
int result = reinterpret_cast<int>(ShellExecute(NULL, L"taskbarunpin",
shortcut, NULL, NULL, 0));
return result > 32;
}
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
Seems pretty straightforward if you know the shortcut. For me though this is not sufficient, I also need to iterate over existing buttons and unpin and repin them on different desktops.
In the comments of a Code Project article it says all you have to do is create a symbolic link in the folder "C:\Users\Username\AppData\Roaming\Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar".
But it appears to generally be unsociable practice, as the other comments here have noted.
You can pin/unpin apps via Windows Shell verbs:
http://blogs.technet.com/deploymentguys/archive/2009/04/08/pin-items-to-the-start-menu-or-windows-7-taskbar-via-script.aspx
For API, there is a script-friendly COM library for working with the Shell:
http://msdn.microsoft.com/en-us/library/bb776890%28VS.85%29.aspx
Here is an example written in JScript:
// Warning: untested and probably needs correction
var appFolder = "FOLDER CONTAINING THE APP/SHORTCUT";
var appToPin = "FILENAME OF APP/SHORTCUT";
var shell = new ActiveXObject("Shell.Application");
var folder = shell.NameSpace(appFolder);
var folderItem = folder.ParseName(appToPin);
var itemVerbs = folderItem.Verbs;
for(var i = 0; i < itemVerbs.Count; i++)
{
// You have to find the verb by name,
// so if you want to support multiple cultures,
// you have to match against the verb text for each culture.
if(itemVerbs[i].name.Replace(/&/, "") == "Pin to Start Menu")
{
itemVerbs[i].DoIt();
}
}
Just to put some links on the info as microsoft now offer an official documentation on "Taskbar Extensions" :
A small set of applications are pinned
by default for new installations.
Other than these, only the user can
pin further applications; programmatic
pinning by an application is not
permitted.
So Kevin Montrose answer is the correct one : DON'T.
It works, but not for all OS, e.g. Windows 10:
[DllImport("kernel32.dll")]
private static extern IntPtr LoadLibrary(string dllName);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern int LoadString(IntPtr hInstance, uint uID, StringBuilder lpBuffer, int nBufferMax);
private static void PinUnpinTaskBar(string filePath, bool pin)
{
if (!File.Exists(filePath))
throw new FileNotFoundException(filePath + " not exists!");
int MAX_PATH = 255;
var actionIndex = pin ? 5386 : 5387; // 5386 is the DLL index for"Pin to Tas&kbar", ref. http://www.win7dll.info/shell32_dll.html
StringBuilder szPinToStartLocalized = new StringBuilder(MAX_PATH);
IntPtr hShell32 = LoadLibrary("Shell32.dll");
LoadString(hShell32, (uint)actionIndex, szPinToStartLocalized, MAX_PATH);
string localizedVerb = szPinToStartLocalized.ToString();
// create the shell application object
dynamic shellApplication = Activator.CreateInstance(Type.GetTypeFromProgID("Shell.Application"));
string path = Path.GetDirectoryName(filePath);
string fileName = Path.GetFileName(filePath);
dynamic directory = shellApplication.NameSpace(path);
dynamic link = directory.ParseName(fileName);
dynamic verbs = link.Verbs();
for (int i = 0; i < verbs.Count(); i++)
{
dynamic verb = verbs.Item(i);
if ((pin && verb.Name.Equals(localizedVerb)) || (!pin && verb.Name.Contains(localizedVerb)))
{
verb.DoIt();
break;
}
}
}
I found there is no offical API to do that, but someone has do it through VBScript.
http://blog.ananthonline.net/?p=37
Thanks.
this folder contains shortcut of pinned application
C:\Users\Your-User-Name\AppData\Roaming\Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar