フォームの内部のドラッグでウィンドウを移動する - タイトルバーのないフォームの移動 - C#

概要

フォームを移動する場合、通常はフォームのタイトルバーをドラッグして移動します。 そのため、タイトルバーのないフォームではフォームを移動することができません。 この記事では、フォームの内部をドラッグして移動できるフォームを実装します。
ダブルクリックイベントもハンドルできる改良版はこちらの記事を参照してください。

サンプルプログラム

フォームを作成し、WindowsAPIの定義をします。さらにフォームのMouseDownイベントに以下のコードを記述します。

コード

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace DraggingMove
{
  public partial class Form1 : Form
  {
    const int WM_SYSCOMMAND = 0x112;   
    const int SC_MOVE = 0xF010;   

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

    public Form1()
    {
      InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

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


著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2024-01-06
作成日: 2010-02-17
iPentec all rights reserverd.