Click to See Complete Forum and Search --> : GetOpenFilename Crashes


Quell
July 20th, 2006, 01:12 PM
Hello.
I have the following code, but it crashes with and access violation error:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
#include <commctrl.h>
#include <SHELLAPI.H>
#include <tchar.h>
#include <Dbghelp.h>
#include <cstring>
#pragma comment(lib,"Dbghelp.lib")

OPENFILENAME ofn;

void GetFileName()
{
memset(&ofn,0,sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hInstance = NULL;
ofn.hwndOwner = GetActiveWindow();
ofn.lpstrFile = _T("\0dllfilehere");
ofn.nMaxFile = MAX_PATH;
ofn.lpstrTitle = _T("Open\0");
ofn.nFilterIndex = 0;
ofn.lpstrDefExt = NULL;
ofn.Flags = OFN_FILEMUSTEXIST;
ofn.lpstrFilter = _T("*.dll\0\0");
GetOpenFileName(&ofn);
return;
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
GetFileName();
return 0;
}

Any ideas why?

golanshahar
July 20th, 2006, 01:35 PM
You didn’t set the ofn.lpstrFile variable:



TCHAR szFile[MAX_PATH]={0};
memset(&ofn,0,sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hInstance = NULL;
ofn.hwndOwner = GetActiveWindow();
ofn.lpstrFile = _T("\0dllfilehere");
ofn.nMaxFile = MAX_PATH;
ofn.lpstrTitle = _T("Open\0");
ofn.lpstrFile = szFile;
ofn.nFilterIndex = 0;
ofn.lpstrDefExt = NULL;
ofn.Flags = OFN_FILEMUSTEXIST;
ofn.lpstrFilter = _T("*.dll\0\0");
GetOpenFileName(&ofn);

szFile will hold the selected file name.

Cheers

Quell
July 20th, 2006, 07:13 PM
Thx alot that was it:D
[EDIT]
Slight problem:

char *ansistr;
WideCharToMultiByte(CP_ACP, 0,szFile, -1,ansistr,0,NULL,NULL);
MessageBoxA(0,ansistr,"test",0);

Any ideas why i get empty string?
Thx

golanshahar
July 21st, 2006, 01:54 AM
Thx alot that was it:D
[EDIT]
Slight problem:

char *ansistr;
WideCharToMultiByte(CP_ACP, 0,szFile, -1,ansistr,0,NULL,NULL);
MessageBoxA(0,ansistr,"test",0);

Any ideas why i get empty string?
Thx

ansistr should be allocated!

anyway look at this FAQ: How to convert between ANSI and UNICODE strings? (http://www.codeguru.com/forum/showthread.php?t=231165)

Cheers