Using the Open File Common Dialog Box


with Ada.Text_IO; use Ada.Text_IO;
with Ada.Unchecked_Conversion;
with System;

with Interfaces.C; use Interfaces.C;

with Win32.Winmain;
with Win32.Commdlg;


procedure GetOpenFileName is
   use type Win32.BOOL;

   function To_LPSTR is
      new Ada.Unchecked_Conversion (System.Address, Win32.LPSTR);
   function To_LPCSTR is
      new Ada.Unchecked_Conversion (System.Address, Win32.LPCSTR);

   bIsSuccess        : Win32.BOOL;
   tmpOpenFileStruc  : aliased Win32.Commdlg.OPENFILENAME;
   szFile            : char_array(0..255) := ( others => nul);
   szFileTitle       : char_array(0..255) := ( others => nul);
   szTitle           : char_array := To_C("Open a text file");
   szDefExt          : char_array := To_C("*.txt");
   szFilter          : char_array := "Text" & nul & "*.txt" & nul &   -- Filter Name & nul & Filter & nul &
                                     nul & nul; -- Terminate List of Filters

begin

   Put_Line("Testing Common Dialog Box - Open File");

   tmpOpenFileStruc.lStructSize       :=  (Win32.Commdlg.OPENFILENAME'Size + 1)/System.Storage_Unit;
   tmpOpenFileStruc.hwndOwner         :=  System.Null_Address;
   tmpOpenFileStruc.hInstance         :=  Win32.WinMain.Get_Hinstance;
   tmpOpenFileStruc.lpstrFilter       :=  To_LPCSTR(szFilter'Address);
   tmpOpenFileStruc.lpstrCustomFilter :=  null;
   tmpOpenFileStruc.nMaxCustFilter    :=  0;
   tmpOpenFileStruc.nFilterIndex      :=  1;
   tmpOpenFileStruc.lpstrFile         :=  To_LPSTR(szFile'Address);
   tmpOpenFileStruc.nMaxFile          :=  szFile'Length;
   tmpOpenFileStruc.lpstrFileTitle    :=  To_LPSTR(szFileTitle'Address);
   tmpOpenFileStruc.nMaxFileTitle     :=  szFileTitle'Length;
   tmpOpenFileStruc.lpstrInitialDir   :=  null;
   tmpOpenFileStruc.lpstrTitle        :=  To_LPCSTR(szTitle'Address);
   tmpOpenFileStruc.nFileOffset       :=  0;
   tmpOpenFileStruc.nFileExtension    :=  0;
   tmpOpenFileStruc.lpstrDefExt       :=  To_LPCSTR(szDefExt'Address);
   tmpOpenFileStruc.lCustData         :=  0;
   tmpOpenFileStruc.lpfnHook          :=  null;
   tmpOpenFileStruc.lpTemplateName    :=  null;
   tmpOpenFileStruc.Flags             :=  0;

   bIsSuccess := Win32.Commdlg.GetOpenFileName(tmpOpenFileStruc'Unchecked_Access);

   if bIsSuccess = Win32.False then
       Put_Line("GetOpenFileName failed:");
       Put_Line("Use the API call CommDlgExtendedError for more information.");
   else
      Put_Line(To_Ada(szFile));
   end if;

end GetOpenFileName;

Contributed by: David Botton and David Marceau
Contributed on: March 8, 1999
License: Public Domain
Back