Open program by dragging file "onto it"

General FreeBASIC programming questions.
nuxpergrandis
Posts: 3
Joined: Jun 29, 2020 5:18

Open program by dragging file "onto it"

Postby nuxpergrandis » Jun 29, 2020 5:25

Hey everyone.

I have a question regarding opening files. I experimented a lot with the options you have to open and save files as well as some shell-commands. But my question is (and I couldn't find an answer to this yet):

Can I make a FreeBASIC program that can "open" a file in a sense most windows applications can do nowadays?
If you drag a txt file onto a text editor, usually the editor will start running and automatically display the file.
If you right-click a txt file you can choose an application to open it with and the same would happen.

Is there a possibility to write this or maybe even something preexisting code?

Thank you in advance!
Xusinboy Bekchanov
Posts: 254
Joined: Jul 26, 2018 18:28

Re: Open program by dragging file "onto it"

Postby Xusinboy Bekchanov » Jun 29, 2020 13:36

It's all there are in my program, you can see: https://github.com/XusinboyBekchanov/VisualFBEditor
jj2007
Posts: 1718
Joined: Oct 23, 2016 15:28
Location: Roma, Italia
Contact:

Re: Open program by dragging file "onto it"

Postby jj2007 » Jun 29, 2020 14:25

Windows only - see end of WM_CREATE handler:

Code: Select all

#Include "windows.bi"   ' JJ 29.6.2020
Dim Shared as Handle hEdit               ' bat@\AllBasics\FreeBasic\TinyFB.bat
Function WndProc(hWnd As HWND, msg As  UINT, wParam As WPARAM, lParam As LPARAM) As LRESULT
  Dim As RECT rc
  Dim As PAINTSTRUCT ps
  Dim As HANDLE PtDC
  Dim As HMENU hMenu, hPopup, hEsi
  Select Case msg
  Case WM_CREATE
   hMenu=CreateMenu()               ' create the main menu
   hPopup=CreatePopupMenu()               ' create a sub-menu
   AppendMenu(hMenu, MF_POPUP, hPopup, "&File")      ' add it to the main menu
   AppendMenu(hPopup, MF_STRING, 101, "&Open")       ' one more main item
   hEsi=CreatePopupMenu()               ' create a sub-menu
   AppendMenu(hEsi, MF_STRING, 121, "&sources")      ' fill it
   AppendMenu(hEsi, MF_STRING, 122, "&includes")      ' with various
   AppendMenu(hEsi, MF_STRING, 123, "&DLLs")         ' options
   AppendMenu(hPopup, MF_POPUP, hEsi, "&Dir")      ' and add it to the main menu as "Dir"
   AppendMenu(hPopup, MF_STRING, 102, "&Save")       ' one more main item
   AppendMenu(hPopup, MF_STRING, 103, "E&xit")       ' one more main item
   SetMenu(hWnd, hMenu)               ' attach menu to main window
   hEdit=CreateWindowEx(WS_EX_CLIENTEDGE, "edit", "Hello, I am an edit control",_
   WS_CHILD Or WS_VISIBLE or ES_MULTILINE, 0, 0, 100, 100, hWnd, 100, 0, 0)
   If Open(Command$(1) For Binary Access Read As #1) = 0 Then
      Dim As UByte file_char ( LOF(1))
      Get #1, , file_char()
      Close #1
      SendMessage(hEdit, WM_SETTEXT, 0, @file_char(0))
   endif

  Case WM_COMMAND
   Select Case wParam
       Case 101: MessageBox(hWnd, "Open not implemented", 0, MB_OK)
       Case 102: MessageBox(hWnd, "Save not implemented", 0, MB_OK)
       Case 121: MessageBox(hWnd, "No *.bas files found", 0, MB_OK)
       Case 122: MessageBox(hWnd, "No *.inc files found", 0, MB_OK)
       Case 123: MessageBox(hWnd, "No *.dll files found", 0, MB_OK)
       Case 103: SendMessage(hWnd, WM_CLOSE, 0, 0)
   End Select
  Case WM_KEYDOWN
     if wParam=VK_ESCAPE then SendMessage(hWnd, WM_CLOSE, 0, 0)
  Case WM_SIZE
   GetClientRect(hWnd, @rc)
   MoveWindow(hEdit, 3, 28, rc.right-6, rc.bottom-30, 0)
  Case WM_DESTROY
      PostQuitMessage(0)
  End Select
  return DefWindowProc(hwnd, msg, wParam, lParam)
End Function

Function WinMain(hInstance As HINSTANCE, hPrevInstance As HINSTANCE, lpCmdLine As LPSTR, nShowCmd As Integer) As Integer
  Dim As WNDCLASSEX wc
  Dim As MSG msg
  Dim As string classname="FbGui"
  Dim As HANDLE hIconLib, hDll
  type pCall as function (xy as any ptr) as long
  Dim As pCall pGetVersion
  type DLLVERSIONINFO
   cbSize as long
   dwMajorVersion as long
   dwMinorVersion as long
   dwBuildNumber as long
   dwPlatformID as long
  end type
  Dim As DLLVERSIONINFO dvi
  dvi.cbSize=sizeof(DLLVERSIONINFO)
  hIconLib=LoadLibrary("shell32")
  wc.hIcon = LoadIcon(hIconLib, 239)   ' get the butterfly icon
  FreeLibrary(hIconLib)
  hDll=LoadLibrary("ComCtl32")
  pGetVersion=GetProcAddress(hDll, "DllGetVersion")
  pGetVersion(@dvi)
  if @dvi.dwMajorVersion then print "Using common controls version ";str(dvi.dwMajorVersion);".";str(dvi.dwMinorVersion)
  FreeLibrary(hDll)
  wc.cbSize = sizeof(WNDCLASSEX)
  wc.hbrBackground = COLOR_BTNFACE+1
  wc.hCursor = LoadCursor(0, IDC_ARROW)
  wc.hIconSm = wc.hIcon
  wc.hInstance = hInstance
  wc.lpfnWndProc = @WndProc
  wc.lpszClassName = StrPtr(classname)
  wc.style = CS_HREDRAW Or CS_VREDRAW
  RegisterClassEx(@wc)
  if CreateWindowEx(0, wc.lpszClassName, "Hello World",_
   WS_OVERLAPPEDWINDOW Or WS_VISIBLE, (GetSystemMetrics(SM_CXSCREEN) / 2) - 150,_
   (GetSystemMetrics(SM_CYSCREEN) / 2) - 150, 300, 300, 0, 0, hInstance, 0)=0 then
          MessageBox(0, "Creating hMain failed miserably", 0, MB_OK)
          return 0
  End If

  While GetMessage(@msg, 0, 0, 0)
      TranslateMessage(@msg)
      DispatchMessage(@msg)
  Wend

  return msg.wParam
End Function
WinMain(GetModuleHandle(NULL), NULL, COMMAND(), SW_NORMAL)
TJF
Posts: 3604
Joined: Dec 06, 2009 22:27
Location: N47°, E15°
Contact:

Re: Open program by dragging file "onto it"

Postby TJF » Jun 29, 2020 17:20

The code at

https://github.com/freebasic/fbc/blob/1 ... onE110.bas

is cross-platform. It open text files dragged on the icon.

Regards
jj2007
Posts: 1718
Joined: Oct 23, 2016 15:28
Location: Roma, Italia
Contact:

Re: Open program by dragging file "onto it"

Postby jj2007 » Jun 29, 2020 19:26

Seems to be Linux only...
* compiling TmpFb.bas with -t 2000 -s console **
FreeBasic\tmp\TmpFb.bas(17) warning 3(1): Passing different pointer types, at parameter 2 of GTK_WINDOW_SET_TITLE()

Aborting due to runtime error 12 ("segmentation violation" signal)
TJF
Posts: 3604
Joined: Dec 06, 2009 22:27
Location: N47°, E15°
Contact:

Re: Open program by dragging file "onto it"

Postby TJF » Jun 30, 2020 7:41

jj2007 wrote:Seems to be Linux only...
* compiling TmpFb.bas with -t 2000 -s console **
FreeBasic\tmp\TmpFb.bas(17) warning 3(1): Passing different pointer types, at parameter 2 of GTK_WINDOW_SET_TITLE()

Aborting due to runtime error 12 ("segmentation violation" signal)
Your gtk/gtk.bi header doesn't match the parameter list in the source at parameter 2. Why do you think that this is related to the operating system? Why do you compile a GUI program with option -s console?

Note: you've to rename the 'object' variable, since this symbol later became a keyword in FB.

Regards
jj2007
Posts: 1718
Joined: Oct 23, 2016 15:28
Location: Roma, Italia
Contact:

Re: Open program by dragging file "onto it"

Postby jj2007 » Jun 30, 2020 8:07

TJF wrote:Your gtk/gtk.bi header doesn't match the parameter list in the source at parameter 2. Why do you think that this is related to the operating system? Why do you compile a GUI program with option -s console?

Note: you've to rename the 'object' variable, since this symbol later became a keyword in FB.
So we are right in the middle of the usual "what are the exact conditions, like compiler chosen, version of header and library files, commandline options, environment variables etc that will allow to compile my little program"... combined with the accusations: "How dare you put in doubt the Holy Grail of portability? And why the hell do you want a console in a GUI program, that's against the rules!!" ... I love BASIC ;-)

P.S., re object variable: Since I used your original code, does this mean you are using an old FB version, or that you didn't test if your code worked before recommending it here?
TJF
Posts: 3604
Joined: Dec 06, 2009 22:27
Location: N47°, E15°
Contact:

Re: Open program by dragging file "onto it"

Postby TJF » Jun 30, 2020 8:24

jj2007 wrote:So we are right in the middle of the usual "what are the exact conditions, like compiler chosen, version of header and library files, commandline options, environment variables etc that will allow to compile my little program"... combined with the accusations: "How dare you put in doubt the Holy Grail of portability? And why the hell do you want a console in a GUI program, that's against the rules!!" ... I love BASIC ;-)
Why do you think this is FB related? You'll face this issue in every other programming language. Of course, the users of ie. Python do much more to provide matching bindings/binaries. FB users are a bit lazy. They just claim, but do not work together sustainably.

jj2007 wrote:P.S., re object variable: Since I used your original code, does this mean you are using an old FB version, or that you didn't test if your code worked before recommending it here?
I tested the code with the current compiler in 2011. I didn't test with all further compilers/headers since then.

Regards
TJF
Posts: 3604
Joined: Dec 06, 2009 22:27
Location: N47°, E15°
Contact:

Re: Open program by dragging file "onto it"

Postby TJF » Jun 30, 2020 8:38

Here's a version that compiles under fbc 1.07.0 and related headers (or gir_headers)

Code: Select all

' This is file gtk_applicationE110.bas, an example for GTK3
' (C) 2020 by Thomas[ dot ]Freiherr[ at ]gmx{ dot }net
' License GPLv 3
'
' See for details (A simple application)
' http://developer.gnome.org/gtk3/stable/GtkApplication.html
'
' Note: This example doesn't execute on windows XP or below.

'~ #DEFINE __USE_GTK3__
'~ #INCLUDE ONCE "gtk/gtk.bi"
#INCLUDE ONCE "Gir/Gtk-3.0.bi"
#INCLUDE ONCE "Gir/_GObjectMacros-2.0.bi"

SUB new_window (BYVAL app AS GApplication PTR, _
                BYVAL file AS GFile PTR)
  VAR win = gtk_window_new (GTK_WINDOW_TOPLEVEL)
  gtk_window_set_application (GTK_WINDOW (win), GTK_APPLICATION (app))
  gtk_window_set_title (GTK_WINDOW (win), @"Bloatpad")
  VAR scrolled = gtk_scrolled_window_new (NULL, NULL)
  VAR vie = gtk_text_view_new ()
  gtk_container_add (GTK_CONTAINER (scrolled), vie)
  gtk_container_add (GTK_CONTAINER (win), scrolled)

  IF file THEN
    DIM AS gchar PTR contents
    DIM AS gsize length

    IF g_file_load_contents (file, NULL, @contents, @length, NULL, NULL) THEN
      VAR buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (vie))
      gtk_text_buffer_set_text (buffer, contents, length)
      g_free (contents)
    END IF
  END IF

  gtk_widget_show_all (GTK_WIDGET (win))
END SUB

TYPE AS GtkApplication BloatPad
TYPE AS GtkApplicationClass BloatPadClass

G_DEFINE_TYPE (BloatPad, bloat_pad, GTK_TYPE_APPLICATION)

SUB bloat_pad_open CDECL(BYVAL app AS GApplication PTR, _
                         BYVAL files AS GFile PTR PTR, _
                         BYVAL n_files AS gint, _
                         BYVAL hint AS CONST gchar PTR)
  FOR i AS gint = 0 TO n_files - 1
    new_window (app, files[i])
  NEXT
END SUB

SUB bloat_pad_activate CDECL(BYVAL app AS GApplication PTR)
  new_window (app, NULL)
END SUB

SUB bloat_pad_finalize CDECL(BYVAL obj AS GObject PTR)
  G_OBJECT_CLASS (bloat_pad_parent_class)->finalize (obj)
END SUB

SUB bloat_pad_init CDECL(BYVAL app AS BloatPad PTR)
END SUB

SUB bloat_pad_class_init CDECL(BYVAL clas AS BloatPadClass PTR)
  G_OBJECT_CLASS(clas)->finalize = @bloat_pad_finalize

  G_APPLICATION_CLASS(clas)->activate = @bloat_pad_activate
  G_APPLICATION_CLASS(clas)->open = @bloat_pad_open
END SUB

FUNCTION bloat_pad_new () AS BloatPad PTR
  g_type_init ()

  RETURN g_object_new (bloat_pad_get_type (), _
                       @"application-id", @"org.gtk.Test.bloatpad", _
                       "flags", G_APPLICATION_HANDLES_OPEN, _
                       NULL)
END FUNCTION



VAR bloat_pad = bloat_pad_new ()
VAR status = g_application_run (G_APPLICATION (bloat_pad), __FB_ARGC__, __FB_ARGV__)
g_object_unref (bloat_pad)

END status
dodicat
Posts: 6718
Joined: Jan 10, 2006 20:30
Location: Scotland

Re: Open program by dragging file "onto it"

Postby dodicat » Jun 30, 2020 9:27

windows.
Purely drag a text file to a box.

Code: Select all


#include once "windows.bi"
#include once "win/shellapi.bi"  'for drag and drop
#include "win/commctrl.bi"
#include "file.bi"               'for loadfile

Declare Function Blueframe Lib "UxTheme.dll" Alias "SetWindowTheme"(As Any Ptr,As zstring Ptr,As zstring Ptr) As Long
Declare Function main As Long
Declare Function loadFile(As String) As String
declare function checkstring(as string) as long

End main


Dim Shared As String  s
Dim Shared show As Hwnd

Function WndProc ( Byval hWnd As HWND, _
    Byval wMsg As UINT, _
    Byval wParam As WPARAM, _
    Byval lParam As LPARAM ) As LRESULT
    Function = 0

    Select Case wMsg

    Case WM_CREATE 
        Exit Function
       
    Case WM_DROPFILES
        Dim hDrop As HANDLE
        Dim drag_file As zstring * (MAX_PATH+1)  '261
        Dim count As Integer
        Dim i As Integer
        hDrop = Cast( HANDLE, wParam )
        count = DragQueryFile(hDrop,&HFFFFFFFF,drag_file, MAX_PATH )'see msdn
        For i = 0 To count - 1
        DragQueryFile( hDrop, i, drag_file, MAX_PATH )
        Next i
        if loadfile(drag_file)="---ERROR---" then
            dim as string message
            if err=1 then message="FOLDER ERROR"
            if err=2 then message="NON TEXT FILE ERROR"
        messagebox(0,"cannot load "+drag_file,message,0)
        err=0
        exit function
    end if
   
        s+=loadfile( drag_file )  'accumulate dropped files
       
        setWindowText(show,s)
        DragFinish( hDrop )
        Exit Function
       
    Case WM_PAINT
        Dim As PAINTSTRUCT ps
            BeginPaint(hwnd, @ps)
            FillRect(ps.hdc, @ps.rcPaint, CreateSolidBrush(BGR(225,225,255)))
            EndPaint(hWnd, @ps)
       
        Exit Function
       
    Case WM_KEYDOWN
        If Lobyte(wParam) = 27  Then s="": setWindowText(show,"")'clear the box
       
    Case WM_DESTROY
        PostQuitMessage( 0 )
        Exit Function
    End Select
   
    Function = DefWindowProc( hWnd, wMsg, wParam, lParam )   
   
End Function

Function main As Long
    Function=0
    Dim hInstance As HINSTANCE = GetModuleHandle( null )
    Dim wMsg As MSG
    Dim wcls As WNDCLASS     
    Dim hWnd As HWND
 
    With wcls
        .style         = CS_HREDRAW Or CS_VREDRAW Or CS_DROPSHADOW
        .lpfnWndProc   = @WndProc
        .cbClsExtra    = 0
        .cbWndExtra    = 0
        .hInstance     = hInstance
        .hIcon         = LoadIcon( NULL, IDI_APPLICATION )
        .hCursor       = LoadCursor( NULL, IDC_ARROW )
        .hbrBackground = GetStockObject( WHITE_BRUSH )
        .lpszMenuName  = NULL
        .lpszClassName = @"HelloWin"
    End With
   
    If( RegisterClass( @wcls ) = FALSE ) Then
        MessageBox( null, "Failed to register wcls", "Error", MB_ICONERROR )
        End 1
    End If
   
    hWnd = CreateWindowEx( WS_EX_ACCEPTFILES, _
    @"HelloWin", _
    "Drag a text file to box  -- Press <Esc> to refresh", _
    WS_OVERLAPPEDWINDOW, _
    0, _
    0, _
    800, _
    600, _
    NULL, _
    NULL, _
    hInstance, _
    NULL )
    show=CreateWindowEx(0,"EDIT","", ws_border Or WS_VISIBLE Or WS_CHILD Or WS_HSCROLL Or WS_VSCROLL Or ES_AUTOHSCROLL Or ES_AUTOVSCROLL Or ES_MULTILINE, 10, 10,770,540, hwnd, 0, 0, 0 )
    BlueFrame(hwnd,"","")
    ShowWindow( hWnd, SW_SHOW )
    UpdateWindow( hWnd )
   
    While( GetMessage( @wMsg, NULL, 0, 0 ) <> FALSE )   
        TranslateMessage( @wMsg )
        DispatchMessage( @wMsg )
    Wend
   
    End wMsg.wParam
End Function

Function loadfile(file As String) As String
   If Fileexists(file)=0 Then Print file;" not found":err=1:return "---ERROR---"
    Var  f=Freefile
    Open file For Binary Access Read As #f
    Dim As String text
    If Lof(f) > 0 Then
        text = String(Lof(f), 0)
        Get #f, , text
    End If
    Close #f
    if checkstring(text)=0 then err=2:return "---ERROR---"
    Return text
End Function

function checkstring(t as string) as long
    for n as long=0 to len(t)-1
        if t[n]>128 then return 0
    next
    return -1
    end function
       
 
jj2007
Posts: 1718
Joined: Oct 23, 2016 15:28
Location: Roma, Italia
Contact:

Re: Open program by dragging file "onto it"

Postby jj2007 » Jun 30, 2020 11:48

TJF wrote:Here's a version that compiles under fbc 1.07.0 and related headers
TmpFb.bas(12) error 23: File not found, "Gir/Gtk-3.0.bi"

The OP, nuxpergrandis, has two posts, so he is a definitely a n00b. Throwing untested examples at him, or code that requires external libraries without even giving him a download URL, is pretty arrogant, especially in a BASIC forum.

@dodicat: works fine!
TJF
Posts: 3604
Joined: Dec 06, 2009 22:27
Location: N47°, E15°
Contact:

Re: Open program by dragging file "onto it"

Postby TJF » Jun 30, 2020 12:20

jj2007 wrote:TmpFb.bas(12) error 23: File not found, "Gir/Gtk-3.0.bi"
Obviously you didn't install the headers yet. Perhaps you want to comment the Gir headers, and uncomment original in the two lines above?
jj2007 wrote:The OP, nuxpergrandis, has two posts, so he is a definitely a n00b.
Why do you know that the OP isn't experienced in other programming languages?
jj2007 wrote:Throwing untested examples at him, or code that requires external libraries without even giving him a download URL, is pretty arrogant, especially in a BASIC forum.
  • We're in General forum, not in Beginners.
  • It's an original example shipped in the fbc package.
  • Nobody asked for a download link yet, but here you are.
  • You're correct, one of us is arrogant.
nuxpergrandis
Posts: 3
Joined: Jun 29, 2020 5:18

Re: Open program by dragging file "onto it"

Postby nuxpergrandis » Jun 30, 2020 17:51

I wanted to say thanks to everyone posting something!

I picked the windows only version to build upon, my program is already limited to Windows anyway and I believe I can make a good own version of this. Thank you!
grindstone
Posts: 755
Joined: May 05, 2015 5:35
Location: Germany

Re: Open program by dragging file "onto it"

Postby grindstone » Jun 30, 2020 21:16

Why that complicated? It can be done with just one single line of code:

Code: Select all

Shell Chr(34) & Command(1) & Chr(34)
jj2007
Posts: 1718
Joined: Oct 23, 2016 15:28
Location: Roma, Italia
Contact:

Re: Open program by dragging file "onto it"

Postby jj2007 » Jun 30, 2020 21:39

grindstone wrote:Why that complicated? It can be done with just one single line of code:

Code: Select all

Shell Chr(34) & Command(1) & Chr(34)
It seems to me that OP wanted something different:
nuxpergrandis wrote:Can I make a FreeBASIC program that can "open" a file in a sense most windows applications can do nowadays?
If you drag a txt file onto a text editor, usually the editor will start running and automatically display the file.

Return to “General”

Who is online

Users browsing this forum: No registered users and 5 guests