作成 2013.09.28
更新 2013.09.28
PowerShell でデスクトップ上のマウスカーソルの位置を取得する
追加アプリケーションをインストールできない環境で、GUI操作を自動化する際に作ったもの。
コード
mouse_trace.ps1
$provider = New-Object Microsoft.CSharp.CSharpCodeProvider
$params = New-Object System.CodeDom.Compiler.CompilerParameters
$params.GenerateInMemory = $True
$params.TreatWarningsAsErrors = $True
$refs = "System.dll","mscorlib.dll","System.Drawing.dll","System.Windows.Forms.dll"
$params.ReferencedAssemblies.AddRange($refs)

# C Sharp
$txtCode = '
using System;
using System.Drawing;
using System.Windows.Forms;

public class MouseTrace {
	bool cap_stat = false;
	Form f1 = new Form();
	TextBox tb_x = new TextBox();
	TextBox tb_y = new TextBox();
	Button btn1 = new Button();
	Label lbl1 = new Label();
	Color c_on = Color.Green;
	Color c_off = Color.Red;
	System.Timers.Timer tm1 = new System.Timers.Timer(100.0);
	public MouseTrace(){
		Font font1 = new Font("MS ゴシック",16);
		f1.Text = "Mouse Trace";
		tb_x.Font = font1;
		tb_x.Location = new Point(10,10);
		tb_x.Text = "0";
		tb_x.TextAlign = HorizontalAlignment.Center;
		tb_x.Width = 100;
		tb_y.Font = font1;
		tb_y.Location = new Point(tb_x.Right+10,10);
		tb_y.Text = "0";
		tb_y.TextAlign = HorizontalAlignment.Center;
		tb_y.Width = 100;
		btn1.Location = new Point(10,tb_x.Bottom+10);
		btn1.Text = "Mouse Capture";
		btn1.Width = 110;
		btn1.MouseClick += new MouseEventHandler(btn1_MouseClick);
		lbl1.Location = new Point(btn1.Right+10,btn1.Top);
		lbl1.Text = "Off";
		lbl1.ForeColor = c_off;
		lbl1.Font = font1;
		f1.Size = new System.Drawing.Size(tb_y.Right+30,btn1.Bottom+50);
		f1.Controls.Add(tb_x);
		f1.Controls.Add(tb_y);
		f1.Controls.Add(btn1);
		f1.Controls.Add(lbl1);
		tm1.Elapsed += new System.Timers.ElapsedEventHandler(WriteMousePosition);
	}
	public void Show(){
		f1.ShowDialog();
	}
	private void WriteMousePosition(object source, System.Timers.ElapsedEventArgs e){
		// 画面上の絶対座標
		tb_x.Text = Cursor.Position.X.ToString();
		tb_y.Text = Cursor.Position.Y.ToString();
	}
	private void btn1_MouseClick(object sender, MouseEventArgs e){
		if(cap_stat){
			lbl1.ForeColor = c_off;
			lbl1.Text = "Off";
			cap_stat = false;
			tm1.Stop();
		}else{
			lbl1.ForeColor = c_on;
			lbl1.Text = "On";
			cap_stat = true;
			tm1.Start();
		}
	}
}
'

$results = $provider.CompileAssemblyFromSource($params, $txtCode)
$results.Errors
$mAssembly = $results.CompiledAssembly
$i = $mAssembly.CreateInstance("MouseTrace")
$i.Show()
実行
ps1 ファイルを実行できるように設定しておく。
PS C:\> mouse_trace.ps1
「Mouse Capture」をクリックすると実行開始。マウスカーソルがデスクトップ上のどこにあるか絶対座標を取得する。

©2004-2017 UPKEN IPv4