Call Win32 GetOpenFileName from C#

S

SS

I tried a sample code provided in Microsoft .NET on how to make a call to
Win32 GetOpenFileName. It crashed if I call the function, select a file and
close the dialog and repeat the process several times.. I got the following
error :

An unhandled exception of type 'System.NullReferenceException' occurred in
system.windows.forms.dll

Additional information: Object reference not set to an instance of an
object.

Below is the code :

[ StructLayout( LayoutKind.Sequential, CharSet=CharSet.Auto )]
public class OpenFileName
{
public int structSize = 0;
public IntPtr dlgOwner = IntPtr.Zero;
public IntPtr instance = IntPtr.Zero;

public String filter = null;
public String customFilter = null;
public int maxCustFilter = 0;
public int filterIndex = 0;

public String file = null;
public int maxFile = 0;

public String fileTitle = null;
public int maxFileTitle = 0;

public String initialDir = null;

public String title = null;

public int flags = 0;
public short fileOffset = 0;
public short fileExtension = 0;

public String defExt = null;

public IntPtr custData = IntPtr.Zero;
public IntPtr hook = IntPtr.Zero;

public String templateName = null;

public IntPtr reservedPtr = IntPtr.Zero;
public int reservedInt = 0;
public int flagsEx = 0;
}

public class LibWrap
{
[ DllImport( "Comdlg32.dll", CharSet=CharSet.Auto )]
public static extern bool GetOpenFileNameW([ In, Out ] OpenFileName
ofn );
}

private void Test()
{
OpenFileName ofn = new OpenFileName();

ofn.structSize = Marshal.SizeOf( ofn );
ofn.filter = "*.xml" ;
ofn.file = new String( new char[ 256 ]);
ofn.maxFile = ofn.file.Length;
ofn.fileTitle = new String( new char[ 64 ]);
ofn.maxFileTitle = ofn.fileTitle.Length;
ofn.initialDir = "C:\\";
ofn.title = "Open file";
ofn.defExt = "xml";
ofn.flags = 0x00000100;
ofn.file = "*.xml";
ofn.dlgOwner = this.Handle;

if( LibWrap.GetOpenFileNameW( ofn ))
{
}
}

Any idea ?
 
M

Mohamoss

Hi
You might need to set a breakpoint and step into your code line by line to
know exactly which line of code is causing the null reference . This will
help much determining what the problem is.
Mohamed Mahfouz
MEA Developer Support Center
ITworx on behalf of Microsoft EMEA GTSC
 
S

SS

It has no problem until after I clicked "Open" button in the dialog
(OpenFile dialog).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top