GetOpenFileName fails in 64 bit, but works in 32Bit? - windows

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

Related

Kissfftr different results x86 - Atheros AR9331

This is my first question on stackoverflow and my englsich is unfortunately poor. But I want to try it.
A customized routine of twotonetest of kissfft brings on two different systems very different results.
The under ubuntu translated with gcc on x86 program brings the correct values. That with the openWRT SDK translated for the Arduino YUN (Atheros AR9331) program displays incorrect values​​. It seems as if since the definition of FIXED_POINT is ignored.
Defined is:
#define FIXED_POINT 32
the function:
double GetFreqBuf( tBuf * io_pBuf, int nfft)
{
kiss_fftr_cfg cfg = NULL;
kiss_fft_cpx *kout = NULL;
kiss_fft_scalar *tbuf = NULL;
uint32_t ptr;
int i;
double sigpow=0;
double noisepow=0;
long maxrange = SHRT_MAX;
cfg = kiss_fftr_alloc(nfft , 0, NULL, NULL);
tbuf = KISS_FFT_MALLOC(nfft * sizeof(kiss_fft_scalar));
kout = KISS_FFT_MALLOC(nfft * sizeof(kiss_fft_cpx));
/* generate the array from samples*/
for (i = 0; i < nfft; i++) {
//nur einen Kanal, eine Krücke, würde nun auch mit 2 kanälen gehen, aber so ist schneller
if (io_pBuf->IndexNextValue >= (i*2))
ptr = io_pBuf->IndexNextValue - (i*2);
else
ptr = io_pBuf->bufSize - ((i*2) - io_pBuf->IndexNextValue);
tbuf[i] = io_pBuf->aData[ptr] ;
}
kiss_fftr(cfg, tbuf, kout);
for (i=0;i < (nfft/2+1);++i) {
double tmpr = (double)kout[i].r / (double)maxrange;
double tmpi = (double)kout[i].i / (double)maxrange;
double mag2 = tmpr*tmpr + tmpi*tmpi;
if (i!=0 && i!= nfft/2)
mag2 *= 2; /* all bins except DC and Nyquist have symmetric counterparts implied*/
/* if there is power between the frq's, it is signal, otherwise noise*/
if ( i > nfft/96 && i < nfft/32 )
noisepow += mag2;
else
sigpow += mag2;
}
kiss_fft_cleanup();
//printf("TEST %d Werte, noisepow: %f sigpow: %f noise # %fdB\n",nfft,noisepow,sigpow,10*log10(noisepow/sigpow +1e-30) );
free(cfg);
free(tbuf);
free(kout);
return 10*log10(noisepow/sigpow +1e-30);
}
As input samples of 16-bit sound from the same file be used. Results differ for example from-3dB to-15dB. AWhere could you start troubleshooting?
Possibility #1 (most likely)
You are compiling kissfft.c or kiss_fftr.c differently than the calling code. This happens to a lot of people.
An easy way to force the same FIXED_POINT is to edit the kiss_fft.h directly. Another option: verify with some printf debugging. i.e. place the following in various places:
printf( __FILE__ " sees sizeof(kiss_fft_scalar)=%d\n" , sizeof(kiss_fft_scalar) )
Possibility #2
Perhaps the FIXED_POINT=16 code works but the FIXED_POINT=32 code does not because something is being handled incorrectly either inside kissfft or on the platform. The 32 bit fixed code relies on int64_t being implemented correctly.
Is that Atheros a 16 bit processor? I know kissfft has been used successfully on 16 bit platforms, but I'm not sure if FIXED_POINT=32 real FFTs on a 16 bit fixed point has been used.
viel Glück,
Mark

Windows Common File Dialog Will Not Display While Running in Visual Studio 2010 Debugger

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.

shell32.dll: access violation during GetOpenFileName new thread

GetOpenFileName fails with access violation. File must be on DESKTOP and have long name.
Problem occurs only after first successful open of the file. Problem occurs when mouse cursor hovers over file as tool tip about to be displayed.
See the answer below. I'm leaving the original problem description below.
Mike D.
=======================
I'm using GetOpenFileName. I sometimes get a access violation deep inside shell32. The violation never occurs the first time this code is used, it often takes five or six tries. Also it appears that if one selects a file in second or two after the open file window pops up, the violation does not occur. Also, the call stack displayed when I debug this does not include any of my code. It's as if some independent thread is waking up to do something.
Any insights into how I might debug this greatly appreciated!
I made a "hello" world app exhibiting the same behavior. It, however, requires many more tries before it fails. It also seems that one has to switch directories before it will fail.
The GOFN is done from a thread created just for that purpose. Below is the code from the "hello world" app.
typedef struct
{
public:
HWND hWnd;
HINSTANCE hInst;
} def_params, *p_params;
DWORD WINAPI ReadLogFile_DataRecorderThread (PVOID pvoid);
void ReadLogFile_DataRecorder (HWND hWnd, HINSTANCE hInst) // ***************************
{
static def_params Params;
Params.hWnd = hWnd;
Params.hInst = hInst;
HANDLE T = CreateThread (NULL,0,ReadLogFile_DataRecorderThread,&Params,0,NULL);
CloseHandle (T);
return;
}
DWORD WINAPI ReadLogFile_DataRecorderThread (PVOID pvoid)
{
p_params P = (p_params) pvoid;
HWND hWnd = P->hWnd;
HINSTANCE hInst = P->hInst;
char ReadLogFileLastDir[256];
// static def_OpenFileHook Hook;
OPENFILENAME ofn;
char fn[MAX_PATH]="\0";
char filter[32]="Text Files\0*.TXT;\0\0";
char title[]="Open IMC Data Recorder Log File";
char defext[]="TXT";
int status;
// Get File Name
fn[0] = '\0';
ReadLogFileLastDir[0] = '\0';
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = hWnd;
ofn.hInstance = hInst;
ofn.hInstance = (HINSTANCE) GetWindowLong (hWnd, GWL_HINSTANCE);
ofn.lpstrFilter = filter;
ofn.nFilterIndex = 0;
ofn.lpstrCustomFilter = NULL ;
ofn.nMaxCustFilter = 0 ;
ofn.lpstrFile = fn;
ofn.nMaxFile = sizeof(fn);
ofn.lpstrFileTitle = NULL;
if (ReadLogFileLastDir[0] == '\0')
{
SHGetSpecialFolderPath (NULL,ReadLogFileLastDir,0x0005,false);
};
ofn.lpstrInitialDir = ReadLogFileLastDir;
ofn.lpstrTitle = title;
ofn.Flags = OFN_FILEMUSTEXIST |
OFN_PATHMUSTEXIST |
OFN_EXPLORER |
// OFN_ENABLETEMPLATE |
OFN_ENABLESIZING |
// OFN_ENABLEHOOK |
OFN_READONLY;
ofn.lpstrDefExt = NULL;
ofn.lpfnHook = NULL; // Hook.DialogHook; // hook routine
ofn.lCustData = NULL; // (long) &Hook; // data for hook routine
ofn.lpTemplateName = NULL; // MAKEINTRESOURCE(IDD_HOOKFILEOPEN);
ofn.nFileOffset = 0 ;
ofn.nFileExtension = 0 ;
ofn.lpstrDefExt = defext;
status = GetOpenFileName (&ofn);
int S;
S = CommDlgExtendedError();
return 0;
}
When it fails, the call stack looks like this...
SHELL32! 7ca4e035()
SHELL32! 7cb2dc16()
SHELL32! 7cb2dd5a()
SHELL32! 7cb27361()
SHELL32! 7c9f40a3()
BROWSEUI! 75f81b9a()
SHLWAPI! 77f69548()
NTDLL! 7c927545()
NTDLL! 7c927583()
NTDLL! 7c927645()
NTDLL! 7c92761c()
KERNEL32! 7c80b50b()
Sorry but I am unable to get symbols for these as I have an old Visual C++ :-(
It appears to me that the problem occurs when the GOFN stuff is about to open the popup describing the file as the mouse cursor hovers over the file name.
The set of circumstances causing the problem are somewhat weird. Experiments show one has to do the following in the GOFN window:
Open a file on the DESKTOP
Hover over a long file name
If I do this twice, it always fails. The file name I used was
IMCLOG_20120323_1658_-_20120324_0653_CST_+DST_E2_2_second.TXT
I tried the same thing with NOTEPAD and the same problem occurs!
I found numerous reports of the same problem. For example:
Social.MSDN Problem report
CodeProject question
CodeGuru thread
There was also a Google cached link to a since-deleted MS Connect bug report. As you discovered, the problem seems to be particular to files in the Desktop.
The only suggested solution I found is to call CoInitializeEx(NULL) at the start of the thread, and call CoUninitialize() at the end, so that's worth trying.
Also, the MSDN documentation for GetOpenFileName() says:
Starting with Windows Vista, the Open and Save As common dialog boxes have been superseded by the Common Item Dialog.
So it may be worth discarding GetOpenFileName() completely.

How to use VerQueryValue?

I've an exe that will need to retrieve version infomation from a specific dll (ex : FileDescription). My codes already called the GetFileVersionInfoSize and GetFileVersionInfo. But I'm not sure how to apply the VerQueryValue, even after going through http://msdn.microsoft.com/en-us/library/ms647464(v=vs.85) and other examples.
Can someone explain/shed some light on how to apply VerQueryValue and its usage? Thanks.
To get the FileDescription via VerQueryValue, just copy and paste the example code from the VerQueryValue documentation, and modify it as appropriate.
The basic idea behind that example code is:
Use the second form (\VarFileInfo\Translation) to get the list of translations.
Then use the third form (\StringFileInfo\lang-codepage\string-name) to get the string(s).
(The first form () is just for the VS_FIXEDFILEINFO, a set of numerical values for parts of the version number, the flags, etc.)
The example code gets the FileDescription for each language. If you know you only have one language (e.g., because you're looking at your own app, and it isn't translated), you can skip the loop and just return the first one. For more general use, you want to pick the best match for the user's language and return that one.
This is a working example, after many try and errors. I'm using Borland C++, so minor details may need to be changed for incompabible environments.
#include <Windows.h>
std::string GetAppVersion()
{
DWORD dwHandle;
TCHAR fileName[MAX_PATH];
GetModuleFileName(NULL, fileName, MAX_PATH);
DWORD dwSize = GetFileVersionInfoSize(fileName, &dwHandle );
TCHAR buffer[dwSize];
VS_FIXEDFILEINFO* pvFileInfo = NULL;
UINT fiLen = 0;
if ((dwSize > 0) && GetFileVersionInfo(fileName, dwHandle, dwSize, &buffer))
{
VerQueryValue(&buffer, L"\\", (LPVOID*)&pvFileInfo, &fiLen);
}
if (fiLen > 0)
{
char buf[25];
int len = sprintf(buf, "%hu.%hu.%hu.%hu",
HIWORD(pvFileInfo->dwFileVersionMS),
LOWORD(pvFileInfo->dwFileVersionMS),
HIWORD(pvFileInfo->dwFileVersionLS),
LOWORD(pvFileInfo->dwFileVersionLS)
);
return std::string(buf, len);
}
else
{
return std::string("(Unknown)");
}
}

Windows 7 - Taskbar - Pin or Unpin Program Links

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

Resources