Tuesday, July 20, 2010

Drag and Drop using Watir:

I had hard time doing this since none of the posts on the net worked. There are couple of posts which talks about it and has methods as well but there is no complete step by step information or guide. So i thought i would add one here and this is how I did it for IE.
Go to element.rb file of WATIR library and this is where all IE actions reside. This should be at C:\ruby\lib\ruby\gems\1.8\gems\watir-1.6.5\lib\watir if u have installed ruby on c:\
Add below code for supporting drag and drop functionality
def top_edge
assert_exists
assert_enabled
ole_object.getBoundingClientRect.top.to_i
end
def top_edge_absolute
top_edge + page_container.document.parentWindow.screenTop.to_i
end
def left_edge
assert_exists
assert_enabled
ole_object.getBoundingClientRect.left.to_i
end
def left_edge_absolute
left_edge + page_container.document.parentWindow.screenLeft.to_i
end
def right_click
x = left_edge_absolute
y = top_edge_absolute
#puts "x: #{x}, y: #{y}"
WindowsInput.move_mouse(x, y)
WindowsInput.right_click
end
def left_click
x = left_edge_absolute
y = top_edge_absolute
#puts "x: #{x}, y: #{y}"
# need some extra push to get the cursor in the right area
WindowsInput.move_mouse(x + 2, y + 2)
WindowsInput.left_click
end
def drag_drop(target, src_offset=1, dst_offset=1)
drag_x = left_edge_absolute + src_offset
drag_y = top_edge_absolute + src_offset
drop_x = target.left_edge_absolute + dst_offset
drop_y = target.top_edge_absolute + dst_offset
WindowsInput.move_mouse(drag_x, drag_y)
WindowsInput.left_down
WindowsInput.move_mouse(drop_x, drop_y)
WindowsInput.left_up
end
Many sites will give you this code but below methods are critical here and none talks about it
def left_down
leftdown = create_mouse_input(MOUSEEVENTF_LEFTDOWN)
send_input( [leftdown] )
end
def left_up
leftup = create_mouse_input(MOUSEEVENTF_LEFTUP)
send_input( [leftup] )
end
Now you are all set for it to work. Use it like
$ie.link(:href,"any url1").drag_drop($ie.link(:href,"any url2"),1,100)
any url1 is object to be dragged and any url 2 is where it needs to be dropped. Drag and Drop objects can be same or different. It will be same if you want to move only one object. 1 is source offset i.e. starting position and 100 is destination offset i.e. ending position. Both offsets are not mandatory.
ie.div(:id, 'src').drag_drop(ie.div(:id, 'dst'))

2 comments:

  1. Thanks for sharing this

    ReplyDelete
  2. Hi can you please sent me the drag and drop code in watir...
    if it is this ie.div(:id, 'src').drag_drop(ie.div(:id, 'dst')) ...it is not working.

    Please n thanks

    ReplyDelete