新規作成日 2021-12-25
最終更新日
C# WPFで作成したプログラムを実行して表示されるウィンドウ内でクリックすると、クリックした位置が表示されるプログラムです。
ウィンドウ内でクリックした位置を取得するために、MouseEventArgs.GetPositionメソッドを使用します。
「空のプロジェクト」テンプレートから、 開始する場合、MouseEventArgs.GetPositionメソッドは、どこかの時点(.Net Framework 3.0と.Net Framework 4.0の間のどこか)で、Sysetem.Xaml アセンブリに移動していることに注意が必要です。
参考
C#
// ===============================================================================
// ウィンドウ内でマウスをクリックすると、マウスのウィンドウ内の座標を表示される
// .Net Framework 4.72で、MouseEventArgs.GetPositionメソッドを使用するためにには、
// Sysetem.Xaml アセンブリ参照が必要なことに注意。
// ===============================================================================
using System;
using System.Windows;
using System.Windows.Input;
namespace HandleAnEvent_GetPosition
{
class GetPosition
{
[STAThread]
public static void Main()
{
Application app = new Application();
Window win = new Window();
win.Title = "Handle An Event";
win.Height = 200;
win.Width = 500;
win.MouseDown += WindowOnMouseDown;
app.Run(win);
}
static void WindowOnMouseDown(object sender, MouseButtonEventArgs args)
{
Window win = sender as Window;
string strMessage =
string.Format("{0} ボタンで、ウィンドウの({1}) をクリックした。",
args.ChangedButton, args.GetPosition(win));
win.Content= strMessage;
}
}
}
アセンブリ参照は、以下の5つを追加しています。
- PresentationCore
- PresentationFramework
- System
- WindowsBase
- System.Xaml
参考
実行結果

