10b. wxWidgets – wxFileDrop

OVERVIEW

In this section we look at an example of dragging and dropping files. Unlike dragging and dropping a text object where we need a drag source as well as a target, for file dropping, we only need a drop target. The file will be dragged from outside the application. At a time, multiple files can be selected and dropped, but in the sample code we are only going to handle the first file in the drag queue. Once the drop is done, it loads the contents of the file and displays it in a wxTextCtrl.

SAMPLE CODE

filedragdrop.h
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
   #include <wx/wx.h>
#endif
#include <wx/dnd.h>	
#include <wx/listctrl.h>

class FileDragDrop: public wxFrame {

	public:
		FileDragDrop(const wxString& title);
	private:
		wxTextCtrl *mText;	
};

class FileDropTarget:public wxFileDropTarget {

	public:
		FileDropTarget(wxTextCtrl *txt);
		virtual bool OnDropFiles(wxCoord x, wxCoord y, const wxArrayString &files);

	private:
	  wxTextCtrl *mText;	
};

filedragdrop.cpp
#include "filedragdrop.h"

FileDragDrop::FileDragDrop(const wxString& title):
	wxFrame(NULL, -1, title, wxDefaultPosition, wxSize(500,200)) {
	
	wxPanel *panel = new wxPanel(this,-1);	
	wxBoxSizer *hbox = new wxBoxSizer(wxHORIZONTAL);
	panel->SetSizer(hbox);

	
	mText = new wxTextCtrl(panel, -1, wxT("Drag any text file here"), wxDefaultPosition, wxDefaultSize,
		       	wxTE_PROCESS_ENTER | wxTE_MULTILINE);	

	hbox->Add(mText, 1, wxALL | wxEXPAND, 4);

	FileDropTarget *drop = new FileDropTarget(mText);
	mText->SetDropTarget(drop);

	Center();
}

FileDropTarget::FileDropTarget(wxTextCtrl *txt) {
   mText = txt;
}

bool FileDropTarget::OnDropFiles(wxCoord x, wxCoord y, const wxArrayString  &files) {
	mText->LoadFile(files[0]);
	
	return true;
}



main.h
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
	#include <wx/wx.h>
#endif

class Main: public wxApp {

	public:
		virtual bool OnInit();
};
main.cpp
#include "main.h"
#include "filedragdrop.h"

IMPLEMENT_APP(Main)

bool Main::OnInit() {
	FileDragDrop *app = new FileDragDrop(wxT("File Drag And Drop"));
	app->Show(true);

}

The output is shown below

Be the first to comment

Leave a Reply

Your email address will not be published.


*