フォームの内部のドラッグでウィンドウを移動でき、ダブルクリックも受け付けられるようにする - C#
こちらの方法で、ウィンドウの内部をドラッグすることでフォームを移動させる方法を紹介しましたが、この方法ではフォームでダブルクリック等のイベントが発生しなくなります。今回は、フォームの内部の表面をドラッグしても移動できるフォームをでダブルクリックイベントも受け取れるフォームを実装します。
コード
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)
{
if (e.Button == System.Windows.Forms.MouseButtons.Left) {
if (e.Clicks == 1) {
SetCapture(this.Handle);
ReleaseCapture();
SendMessage(this.Handle, WM_SYSCOMMAND, SC_MOVE | 2, 0);
}
else {
}
}
}
}
}
解説
if (e.Button == System.Windows.Forms.MouseButtons.Left)
により、マウスの左ボタンが押された場合のみウィンドウを移動させるロジックを実行します。
さらに
if (e.Clicks == 1)
により、クリック回数が1回の場合にのみウィンドウを移動させます。ダブルクリックされた場合は e.Clicksが2以上になります。
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用