C# 画像やパネルのドラッグ&ドロップ  [Ubuntu 11.04 + Mono]

Ubuntu + Monoで開発できる環境を作りました。
Ubuntu 11.04にC#(Mono)開発環境のMonoDevelop 2.4をインストールする


画像を貼り付けたピクチャーボックスやパネルをドラッグ&ドロップで移動させるソースを
書いたのでメモしておきます。



ソースの内容



リストからリストへドラッグ&ドロップというサンプルはよく見かけるのですが、
同一パネル内で表示しているオブジェクトの移動というサンプルがなかなか見つけられなかったので・・・



using System;
using System.Drawing;
using System.Windows.Forms;

namespace sample
{
    public class test
    {
        public static void Main(String[] args) {
            Application.Run(new Form1());
        }
    }
    
    class Form1 : Form
    {
        Panel panel;
        bool isDraging = false;
        Point? diffPoint = null;
        
        public Form1()
        {
            this.Width = 500;
            this.Height = 300;
            this.Text = "サンプルプログラム";
            
            this.panel = new Panel();
            this.panel.Location = Location = new Point(10, 10);
            this.panel.Size = new Size(100, 100);
            this.panel.MouseDown += new MouseEventHandler(this.pic_MouseDown);
            this.panel.MouseMove += new MouseEventHandler(this.pic_MouseMove);
            this.panel.MouseUp += new MouseEventHandler(this.pic_MouseUp);
            
            this.panel.BackColor = Color.Blue;
            this.panel.BorderStyle = BorderStyle.Fixed3D;
            
            this.Controls.Add(this.panel);
        }
        
        //マウスを押したときにマウスカーソル変更
        //開始座標を退避
        void pic_MouseDown(object sender, MouseEventArgs e) {
            if (e.Button != MouseButtons.Left) {
                return;
            }
            Cursor.Current = Cursors.Hand;
            isDraging = true;
            diffPoint = e.Location;
        }
        
        //クリック状態でマウスを動かしている時は、開始地点からの差分だけ対象を移動
        void pic_MouseMove(object sender, MouseEventArgs e) {
            if (!isDraging) {
                return;
            }
            
            int x = panel.Location.X + e.X - diffPoint.Value.X;
            int y = panel.Location.Y + e.Y - diffPoint.Value.Y;
            
            panel.Location = new Point(x, y);
        }
        
        //マウスを離したときは初期状態に戻す
        void pic_MouseUp(object sender, MouseEventArgs e) {
            if (e.Button != MouseButtons.Left) {
                return;
            }
            Cursor.Current = Cursors.Default;
            isDraging = false;
        }
    }
}




画面に背景色「青」のパネルを貼り、ドラッグ&ドロップで表示している位置を移動します。




動作サンプル



こんな感じです。

[広告] VPS


多分、Windowsでも問題なく動いてくれるかと思います。



【参考URL】

第22回 ドラッグ&ドロップ
http://homepage1.nifty.com/rucio/main/dotnet/shokyu/standard22.htm

待機状態のマウス・カーソルを表示するには?
http://www.atmarkit.co.jp/fdotnet/dotnettips/134waitcursor/waitcursor.html






関連記事

プロフィール

Author:symfo
blog形式だと探しにくいので、まとめサイト作成中です。
https://symfo.web.fc2.com/

PR

検索フォーム

月別アーカイブ