c# - 如何通过单击鼠标更改 wpf 中的窗口位置

标签 c# wpf

我需要在单击鼠标时更改窗口的位置。 这是代码。

private void Button_Click(object sender, RoutedEventArgs e)
{
    for(int i=0; i<50; i++)
    {
        this.Top -= i; 
        this.Left -= i;
    } 
}

但是每当我运行这个程序时,只显示最后一个位置。我的意图是连续移动它直到循环结束。

最佳答案

最后我自己找到了答案。正如我所料,它工作得很好。我使用了 SynchronizationContext,它可以发布操作来更新 UI 线程上的控件。

    public partial class Splash : Window
    {
        SynchronizationContext sc;
        System.Timers.Timer t;
        double i=0;
        double tempTop;
        double angle = 0;
        public Splash()
        {
            InitializeComponent();
            sc=SynchronizationContext.Current;
        }
        private void Move(object sender, MouseEventArgs e)
        {
            DragMove();
        }

        private void btnClose_Click(object sender, RoutedEventArgs e)
        {
            Application.Current.Shutdown();
        }

        private void btnMinim_Click(object sender, RoutedEventArgs e)
        {
            this.WindowState = WindowState.Minimized;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {

                l1.Content = "Helicopter Moving";
            if(t!=null)
            {
                t.Stop();
                t.Dispose();
            }
                //for (double i = 0; i < 1; i += 0.05)
                //{
                //    this.Top -= i;
                //    this.Left -= i;
                //    Thread.Sleep(100);
                //}
                //l1.Content = "Helicopter Stopped";
                tempTop = this.Top;
                t = new System.Timers.Timer();
                t.Interval = 10;
                t.Enabled = true;
                t.Elapsed += Change;
                t.Start();

        }
        void Change(object sender, EventArgs e)
        {
            if (i <= 3)
            {
                sc.Post(o =>
                {
                    this.Top = tempTop * (Math.Cos(Math.PI * angle / 180));
                    this.Left -= i;
                    angle = (angle >= 360) ? 0 : ++angle;
                    i = i + 0.01;
                }, null);
            }
            else
            {
                t.Stop();
                i = i * -1;
            }

        }
    }
}

关于c# - 如何通过单击鼠标更改 wpf 中的窗口位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32845366/

相关文章:

c# - 如何在不可点击的链接按钮上显示警告框

c# - 具有自动代理登录的 WebBrowser 控件

c# - 在 linq 查询中处理 Nullable bool

c# - 使用 ItemsSource 和 ItemTemplate 的 WPF 列表框

WPF:将宽度(和高度)设置为百分比值

c# - 绑定(bind)到 UserControl DependencyProperty

c# - 动画对象不能用于动画 RenderTransform

c# - 通过数据键名获取 Gridview 行

接口(interface)实现上的 c# 行为

c# - 需要 DependencyPropertyDescriptor 帮助