マウスカーソルを動かす
using System;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows;
using System.Windows.Interop;
namespace WpfApp
{
/// <summary>
/// MainWindow.xaml の相互作用ロジック
/// </summary>
public partial class MainWindow : Window
{
[DllImport("user32.dll")]
private extern static bool GetCursorPos(out POINT lpPoint);
[DllImport("user32.dll")]
private extern static bool SetCursorPos(int x, int y);
[DllImport("user32.dll")]
private extern static bool GetWindowRect(IntPtr hwnd, out RECT lpRect);
[DllImport("user32.dll")]
private static extern void mouse_event(uint dwFlags, int dx, int dy, int dwData, int dwExtraInfo);
public [[enum]] MouseEventFlags : uint
{
LEFTDOWN = 0x00000002,
LEFTUP = 0x00000004,
MIDDLEDOWN = 0x00000020,
MIDDLEUP = 0x00000040,
MOVE = 0x00000001,
ABSOLUTE = 0x00008000,
RIGHTDOWN = 0x00000008,
RIGHTUP = 0x00000010,
WHEEL = 0x00000800,
XDOWN = 0x00000080,
XUP = 0x00000100
}
/// <summary>
/// コンストラクタ
/// </summary>
public MainWindow()
{
// コンポーネントの初期化
InitializeComponent();
}
/// <summary>
/// Click Close Button
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void BtnClose_Click(object sender, RoutedEventArgs e)
{
RECT rect = new RECT();
// call user32.dll GetWindowRect method
// get current window rect value
if (!GetWindowRect(((HwndSource)HwndSource.FromVisual(this)).Handle, out rect))
{
return;
}
POINT goalPoint = new POINT()
{
X = rect.Right - 20,
Y = rect.Top + 10
};
POINT currentPoint = new POINT();
// call user32.dll GetCursorPos method
// get current cursor position
if (!GetCursorPos(out currentPoint))
{
return;
}
while (currentPoint.X != goalPoint.X || currentPoint.Y != goalPoint.Y)
{
if (currentPoint.X != goalPoint.X)
{
currentPoint.X += currentPoint.X > goalPoint.X ? -1 : 1;
}
if (currentPoint.Y != goalPoint.Y)
{
currentPoint.Y += currentPoint.Y > goalPoint.Y ? -1 : 1;
}
// call user32.dll SetCursorPos method
// move cursor position
SetCursorPos(currentPoint.X, currentPoint.Y);
Thread.Sleep(2);
}
// call user32.dll mouse_event method
// click left button
mouse_event((uint)(MouseEventFlags.LEFTDOWN | MouseEventFlags.LEFTUP), currentPoint.X, currentPoint.Y, 0, 0);
}
/// <summary>
/// point
/// </summary>
public struct POINT
{
public int X { get; set; }
public int Y { get; set; }
}
/// <summary>
/// window rect
/// </summary>
public struct RECT
{
public int Left { get; set; }
public int Top { get; set; }
public int Right { get; set; }
public int Bottom { get; set; }
}
}
}
最終更新:2014年01月25日 11:12