在屏幕上摇动窗体

本文关键字:窗体 屏幕 | 更新日期: 2023-09-27 18:15:00

我想"摇一摇"我的winforms表单来提供用户反馈,就像在很多移动操作系统上使用的效果一样。

我显然可以设置窗口的位置,并来回使用Form1.Location.X等,但这种方法的效果很糟糕。我想要一些更流畅的东西——或者有一种方法可以摇动整个屏幕?

我将只针对Windows 7使用。net 4.5。

使用Hans和Vidstige的建议,我提出了以下建议,当窗口最大化时也有效-我希望我可以选择两个答案,我通过Vidstige为你的答案投票,希望其他人也会这样做。然而,汉斯的回答击中了所有的重点。

两种形式MainFormShakeForm

MainForm代码
 Private Sub shakeScreenFeedback()
        Dim f As New Shakefrm
        Dim b As New Bitmap(Me.Width, Me.Height, PixelFormat.Format32bppArgb)
        Me.DrawToBitmap(b, Me.DisplayRectangle)
        f.FormBorderStyle = Windows.Forms.FormBorderStyle.None
        f.Width = Me.Width
        f.Height = Me.Height
        f.ShowInTaskbar = False
        f.BackgroundImage = b
        f.BackgroundImageLayout = ImageLayout.Center
        f.Show(Me)
        f.Location = New Drawing.Point(Me.Location.X, Me.Location.Y)
        'I found putting the shake code in the formLoad event didn't work
        f.shake()
        f.Close()
        b.Dispose()
    End Sub

ShakeForm代码
Public Sub shake()
    Dim original = Location
    Dim rnd = New Random(1337)
    Const shake_amplitude As Integer = 10
    For i As Integer = 0 To 9
        Location = New Point(original.X + rnd.[Next](-shake_amplitude, shake_amplitude), original.Y + rnd.[Next](-shake_amplitude, shake_amplitude))
        System.Threading.Thread.Sleep(20)
    Next
    Location = original
End Sub

在屏幕上摇动窗体

你试过这样的方法吗?

    private void shakeButton_Click(object sender, EventArgs e)
    {
        Shake(this);
    }
    private static void Shake(Form form)
    {
        var original = form.Location;
        var rnd = new Random(1337);
        const int shake_amplitude = 10;
        for (int i = 0; i < 10; i++)
        {
            form.Location = new Point(original.X + rnd.Next(-shake_amplitude, shake_amplitude), original.Y + rnd.Next(-shake_amplitude, shake_amplitude));
            System.Threading.Thread.Sleep(20);
        }
        form.Location = original;
    }

典型的问题是在表单上有太多的控件,使得绘制速度太慢。因此,只需伪造它,创建一个显示表单位图的无边框窗口,并摇动它。使用窗体的DrawToBitmap()方法创建位图。使用32bppPArgb作为像素格式,它的绘制速度比其他格式快十倍。

您可以使用Windows 7的Aero Shake功能来实现此功能。

你可以看看下面的链接了解更多细节:

http://www.codeproject.com/Articles/36294/Aero-Shake

这里是一个小的工作,你可以尝试一下。

private void button1_Click(object sender, EventArgs e)
    {
        this.Width = this.Width - 10;
        this.Height = this.Height - 10;
        Thread.Sleep(15);
        this.Width = this.Width + 10;
        this.Height = this.Height + 10;
    }