Web検索はbingがおすすめ!

ドラッグによりウィンドウ内で移動可能なパネルを実装する - C#

ドラッグによりウィンドウ内で移動可能なパネルを実装するコードを紹介します。

サンプルプログラム

UI

下図のUIを作成します。フォームにPanelを1つ配置します。

コード

下記のコードを記述します。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;


namespace MovePanel
{
  public partial class FormMain : Form
  {
    const int WM_SYSCOMMAND = 0x0112;
    const int SC_MOVE = 0xF010;
    const int SC_SIZE = 0xF000;

    [DllImport("User32.dll", EntryPoint = "SendMessage")]
    extern static int SendMessageGetTextLength(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);

    [DllImport("User32.dll")]
    public static extern int SendMessage(IntPtr hWnd, int uMsg, int wParam, string lParam);

    [DllImport("User32.dll")]
    public static extern int SendMessage(IntPtr hWnd, int uMsg, int wParam, int lParam);

    [DllImport("User32.dll")]
    public static extern bool SetCapture(IntPtr hWnd);

    [DllImport("user32.dll")]
    public static extern bool ReleaseCapture();

    public FormMain()
    {
      InitializeComponent();
    }

    private void panel1_MouseDown(object sender, MouseEventArgs e)
    {
      SetCapture(panel1.Handle);
      ReleaseCapture();
      SendMessage(panel1.Handle, WM_SYSCOMMAND, SC_MOVE | 2, 0);
    }
  }
}

解説

private void panel1_MouseDown(object sender, MouseEventArgs e)
{
  SetCapture(panel1.Handle);
  ReleaseCapture();
  SendMessage(panel1.Handle, WM_SYSCOMMAND, SC_MOVE | 2, 0);
}
SetCapture関数を呼び出しPanelにマウスイベントをキャプチャーする設定にします。その後SendMessage()を呼び出しPanelに対してウィンドウがメッセージを送信します。今回はコントロールの移動のため、WM_SYSCOMMANDメッセージを送信します。パラメーターにはSC_MOVEを与えます。

実行結果

プロジェクトを実行します。下図のウィンドウが表示されます。


マウスポインタをパネルに乗せドラッグするとパネルが移動します。



ウィンドウサイズを変更しても同じように移動できます。

著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
掲載日: 2014-04-23
iPentec all rights reserverd.