// 相對特定元素座標 Point p = Mouse.GetPosition(e.Source as FrameworkElement); // 轉換為螢幕絕對座標 Point screenPoint = (e.Source as FrameworkElement).PointToScreen(p);
[DllImport("User32")] public extern static void SetCursorPos(int x, int y);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern bool GetCursorPos(out POINT pt);
public struct POINT { public int X; public int Y; public POINT(int x, int y) { X = x; Y = y; } }
private void Window_MouseMove(object sender, MouseEventArgs e) {
POINT p = new POINT();
if (GetCursorPos(out p)) {
txtStat.Text = string.Format("X:{0} Y:{1}", p.X, p.Y);
}
}
private delegate void UpdateProgressBarDelegate(DependencyProperty dp, Object value);
private void Process() {
ProgressBar1.Minimum = 0;
ProgressBar1.Maximum = short.MaxValue;
ProgressBar1.Value = 0;
double value = 0;
UpdateProgressBarDelegate updatePbDelegate = new UpdateProgressBarDelegate(ProgressBar1.SetValue);
do {
value += 1;
Dispatcher.Invoke(updatePbDelegate, DispatcherPriority.Background,
new object[] { ProgressBar.ValueProperty, value });
} while (ProgressBar1.Value != ProgressBar1.Maximum);
}
DispatcherPriority.Background 讓 UI 執行緒有機會處理 Render 排程public Window1() {
InitializeComponent();
DispatcherTimer _mainTimer = new DispatcherTimer();
_mainTimer.Interval = TimeSpan.FromSeconds(1);
_mainTimer.Tick += _mainTimer_Tick;
_mainTimer.IsEnabled = true;
}
void _mainTimer_Tick(object sender, EventArgs e) {
if (progressBar2.Value == progressBar1.Maximum) progressBar2.Value = 0;
progressBar2.Value++;
}
BackgroundWorker/Task 更新進度<ProgressBar Grid.Row="1" Height="20" Width="200" Margin="0,4,0,0"
Name="ProgressBar1" HorizontalAlignment="Center" VerticalAlignment="Top" />
滑鼠座標取得:WPF API 適合相對元素定位,P/Invoke 適合全域/跨進程座標。ProgressBar 更新:Dispatcher.Invoke(Background) 解決同步運算阻塞 UI 不重繪問題;DispatcherTimer 適合非阻塞週期性更新。根據任務性質選擇恰當模式。