My Blog

Drag and drop object between processes

by lupok on giovedì 10 ottobre 2013 13:11
Un semplice esempio che mostra come spostare oggetti mediante drag and drop tra applicazioni Windows Forms, l'oggetto deve essere prima serializzato a stringa mediante XmlSerializer (volendo potaveno essere utilizzati altri serializzatori disponibili in .NET), una volta serializzato l'oggetto puo' essere trasportato su altre applicazioni mediante i meccanismi di drag and drop presenti in Windows Forms per essere poi deserializzato e gestito nella applicazione di destinazione.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
 
namespace DradAndDropBetweenApplication
{
   public partial class FormDragDrop : Form
   {
      public FormDragDrop()
      {
         InitializeComponent();
 
         listBox1.Items.Add(
            new MySharedObject() { Name = "Alberto", Address = "Via Val di Non, 1", Age = 35 });
         
         listBox1.Items.Add
            (new MySharedObject() { Name = "Lupo", Address = "Via Sacco e Vanzetti, 9", Age = 35 });
      }
 
      private void listBox1_DragLeave(object sender, EventArgs e)
      {
         if (listBox1.SelectedItem != null)
            listBox1.Items.Remove(listBox1.SelectedItem);
      }
 
      private void listBox1_DragEnter(object sender, DragEventArgs e)
      {
         if (e.Data.GetDataPresent(DataFormats.Text))
            e.Effect = DragDropEffects.Move;
         else
            e.Effect = DragDropEffects.None;
      }
 
      private void listBox1_DragDrop(object sender, DragEventArgs e)
      {
         listBox1.Items.Add(MySharedObject.DeserializeFromString(
            e.Data.GetData(DataFormats.Text).ToString()));
      }
 
      private void listBox1_MouseDown(object sender, MouseEventArgs e)
      {
         if (listBox1.SelectedItem != null)
            listBox1.DoDragDrop(MySharedObject.SerializeToString(
               (MySharedObject)listBox1.SelectedItem), DragDropEffects.Move);
      }
 
   }
}
DradAndDropBetweenApplication.zip

Blogs Parent Separator My Blog
Author
lupok

My Blog

Tags