Chapter 4. Working With the Clipboard

Table of Contents

Basic Application
Acquiring the Clipboard
Sending Data to the Clipboard
Pasting Data from the Clipboard

Two of the standard FOX widgets, FXText and FXTextField, provide clipboard support out of the box. For example, you can select some text in an FXTextField and then press Ctrl+C to copy that text to the system clipboard. You can also press Ctrl+X to "cut" the selected text to the clipboard, or Ctrl+V to paste text from the clipboard into an FXText or FXTextField widget. The purpose of this tutorial is to demonstrate how to interact with the clipboard programmatically, so that you can integrate additional clipboard support into your FXRuby applications.

Basic Application

In order to illustrate how to integrate cut and paste operations into your application, we'll start from a simple FXRuby application that doesn't yet provide any clipboard support. This application simply presents a list of customers (from some external source).

require 'fox16'
require 'customer'

include Fox

class ClipMainWindow < FXMainWindow
  def initialize(anApp)
    # Initialize base class first
    super(anApp, "Clipboard Example", :opts => DECOR_ALL, :width => 400, :height => 300)

    # Place the list in a sunken frame
    sunkenFrame = FXVerticalFrame.new(self,
			LAYOUT_FILL_X|LAYOUT_FILL_Y|FRAME_SUNKEN|FRAME_THICK, :padding => 0)
    
    # Customer list
    customerList = FXList.new(sunkenFrame, :opts => LIST_BROWSESELECT|LAYOUT_FILL_X|LAYOUT_FILL_Y)
    $customers.each do |customer|
      customerList.appendItem(customer.name, nil, customer)
    end
  end
  
  def create
    super
    show(PLACEMENT_SCREEN)
  end
end

if __FILE__ == $0
  FXApp.new("ClipboardExample", "FXRuby") do |theApp|
    ClipMainWindow.new(theApp)
    theApp.create
    theApp.run
  end
end

We're assuming that the "customer" module defines a Customer class and a global array $customers that contains the list of customers. For a real world application, you might access this information from a database or some other source, but for this example we'll just use a hard-coded array:

# customer.rb

Customer = Struct.new("Customer", :name, :address, :zip)

$customers = []
$customers << Customer.new("Reed Richards", "123 Maple, Central City, NY", 010111)
$customers << Customer.new("Sue Storm", "123 Maple, Anytown, NC", 12345)
$customers << Customer.new("Benjamin J. Grimm", "123 Maple, Anytown, NC", 12345)
$customers << Customer.new("Johnny Storm", "123 Maple, Anytown, NC", 12345)

The goals for the next few sections are to extend this application so that users can select a customer from the list and copy that customer's information to the clipboard, and subsequently paste that information into another copy of the program (or some other clipboard-aware application).