1. 程式人生 > 程式設計 >C#實現窗體抖動的兩種方法

C#實現窗體抖動的兩種方法

本文例項為大家分享了C#實現窗體抖動的具體程式碼,供大家參考,具體內容如下

原理:圍繞中心點運動一圈

C#實現窗體抖動的兩種方法

方法一:通過執行緒實現

需求:需要using System.Threading;名稱空間和button按鈕以及for迴圈

具體程式碼如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;//新增執行緒

namespace Test_Window_jitter
{
  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
    }

    private void Form1_Load(object sender,EventArgs e)
    {
      this.Location = new Point(Screen.PrimaryScreen.WorkingArea.Width/2-this.Width/2,Screen.PrimaryScreen.Bounds.Height/2-this.Height/2);
      button1.BackgroundImage = Image.FromFile("../../img/1.jpg");
      button1.BackgroundImageLayout = ImageLayout.Stretch;
    }

    private void button1_Click(object sender,EventArgs e)
    {
      int x = this.Left;
      int y = this.Top;
      for (int i = 0; i < 3; i++)
      {
        this.Location = new Point(x - 3,y);
        Thread.Sleep(10);//設定執行完上一步停留時間
        this.Location = new Point(x - 3,y - 3);
        Thread.Sleep(10);
        this.Location = new Point(x,y - 3);
        Thread.Sleep(10);
        this.Location = new Point(x + 3,y);
        Thread.Sleep(10);
        this.Location = new Point(x + 3,y + 3);
        Thread.Sleep(10);
        this.Location = new Point(x,y + 3);
        Thread.Sleep(10);
        this.Location = new Point(x - 3,y);
        Thread.Sleep(10);
        this.Location = new Point(x,y);
      }
    }
  }
}

方法二:通過計時器實現

需求:timer控制元件,button按鈕,for迴圈

具體程式碼如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Test_Window_jitter
{
  public partial class Form2 : Form
  {
    public Form2()
    {
      InitializeComponent();
    }

    private void Form2_Load(object sender,EventArgs e)
    {
      this.Location = new Point(Screen.PrimaryScreen.WorkingArea.Width / 2 - this.Width / 2,Screen.PrimaryScreen.Bounds.Height / 2 - this.Height / 2);
    }

    private void button1_Click(object sender,EventArgs e)
    {
      timer1.Start();
    }

    private void timer1_Tick(object sender,EventArgs e)
    {
      int x = this.Left;
      int y = this.Top;
      for (int i = 0; i < 10; i++)
      {
        this.Location = new Point(x - 10,y);
        this.Location = new Point(x - 10,y - 10);
        this.Location = new Point(x,y - 10);
        this.Location = new Point(x + 10,y);
        this.Location = new Point(x + 10,y + 10);
        this.Location = new Point(x,y + 10);
        this.Location = new Point(x - 10,y);
        this.Location = new Point(x,y);
      }
      timer1.Stop();
    }
  }
}

看完記得點贊嗷下期更精彩!

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。