Detecting mouse_down and mouse_move events in a Gtk::DrawingArea

#! /usr/bin/env ruby

# file: rectangle.rb

require 'gtk2'

area = Gtk::DrawingArea.new

area.signal_connect("expose_event") do

  x1 = 100; y1 = 100; x2 = 400; y2 = 200
  area.window.draw_rectangle(area.style.fg_gc(area.state), 1, x1, y1, x2, y2)

end

area.add_events(Gdk::Event::POINTER_MOTION_MASK) 
area.add_events(Gdk::Event::BUTTON_PRESS_MASK) 


area.signal_connect('motion_notify_event') do |item,  event|
  puts "x: %s y: %s button1?: %s"  % [event.x, event.y, event.state.button1_mask?.inspect]
end
area.signal_connect "button_press_event" do |item,event| 
  puts "x: %s y: %s button: %s" % [event.x, event.y, event.button]
end


Gtk::Window.new.add(area).show_all

Gtk.main

Output (extract):

The following output shows the trail of moving the mouse, pressing down on the left mouse button, and then releasing the left mouse button:

x: 141.0 y: 176.0 button1?: false
x: 139.0 y: 176.0 button1?: false
x: 142.0 y: 174.0 button1?: false
x: 142.0 y: 173.0 button1?: false
x: 143.0 y: 173.0 button1?: false
x: 142.0 y: 172.0 button1?: false
x: 142.0 y: 172.0 button: 1
x: 141.0 y: 172.0 button1?: true
x: 140.0 y: 172.0 button1?: true
x: 140.0 y: 171.0 button1?: true
x: 140.0 y: 170.0 button1?: true
x: 140.0 y: 169.0 button1?: true
x: 139.0 y: 168.0 button1?: true
x: 135.0 y: 162.0 button1?: true
x: 135.0 y: 161.0 button1?: true
x: 133.0 y: 161.0 button1?: true
x: 132.0 y: 160.0 button1?: true
x: 131.0 y: 160.0 button1?: true
x: 130.0 y: 160.0 button1?: false
x: 130.0 y: 161.0 button1?: false

The following output shows the trail of moving the mouse and then pressing down on the right mouse button momentarily:

x: 114.0 y: 168.0 button1?: false
x: 113.0 y: 168.0 button1?: false
x: 112.0 y: 168.0 button1?: false
x: 112.0 y: 169.0 button1?: false
x: 112.0 y: 169.0 button: 3
x: 114.0 y: 171.0 button1?: false
x: 115.0 y: 172.0 button1?: false
x: 116.0 y: 173.0 button1?: false
x: 117.0 y: 173.0 button1?: false

Resources