C#模拟MSN窗体抖动的实现代码一般可以采用以下三个步骤:
1.获取窗体当前位置,并定义抖动偏移量;
2.在一定时间内不断改变窗体位置,实现抖动效果;
3.在抖动结束后恢复原始窗体位置。
具体实现步骤如下:
第一步:获取窗体当前位置和定义抖动偏移量
//获取窗口当前位置
Point OldPoint = this.Location;
//定义抖动偏移量,根据需求自定义抖动程度
int Offset = 8;
第二步:循环改变窗口位置,实现抖动效果
//定义变量记录循环次数
int ShakingTime = 0;
//定义抖动时间间隔
int ShakingInterval = 20;
//定义抖动次数,根据需求自定义抖动次数
int ShakingCount = 10;
while (ShakingTime < ShakingCount)
{
//同步刷新窗口位置
this.Location = new Point(OldPoint.X + Offset, OldPoint.Y + Offset);
//等待一定时间间隔后恢复原始位置
System.Threading.Thread.Sleep(ShakingInterval);
this.Location = OldPoint;
System.Threading.Thread.Sleep(ShakingInterval);
//累加循环次数
ShakingTime++;
}
第三步:恢复原始窗口位置
this.Location = OldPoint;
以上就是C#模拟MSN窗体抖动的完整攻略。
下面附上两条示例代码,第一条是在WinForm窗体的Load事件中点击button1按钮时触发抖动效果,第二条是在WPF程序中通过重写OnSourceInitialized方法实现窗体抖动效果:
示例1(WinForm):
private void button1_Click(object sender, EventArgs e)
{
//获取窗口当前位置
Point OldPoint = this.Location;
//定义抖动偏移量
int Offset = 8;
//定义变量记录循环次数
int ShakingTime = 0;
//定义抖动时间间隔
int ShakingInterval = 20;
//定义抖动次数
int ShakingCount = 10;
while (ShakingTime < ShakingCount)
{
//同步刷新窗口位置
this.Location = new Point(OldPoint.X + Offset, OldPoint.Y + Offset);
//等待一定时间间隔后恢复原始位置
System.Threading.Thread.Sleep(ShakingInterval);
this.Location = OldPoint;
System.Threading.Thread.Sleep(ShakingInterval);
//累加循环次数
ShakingTime++;
}
//恢复原始窗口位置
this.Location = OldPoint;
}
示例2(WPF):
protected override void OnSourceInitialized(EventArgs e)
{
base.OnSourceInitialized(e);
//获取窗口句柄
IntPtr hwnd = new System.Windows.Interop.WindowInteropHelper(this).Handle;
//定义抖动偏移量
int Offset = 8;
//定义变量记录循环次数
int ShakingTime = 0;
//定义抖动时间间隔
int ShakingInterval = 20;
//定义抖动次数
int ShakingCount = 10;
//获取窗口矩形
Rect rect = new Rect();
GetWindowRect(hwnd, ref rect);
Point OldPoint = new Point(rect.Left, rect.Top);
while (ShakingTime < ShakingCount)
{
//同步刷新窗口位置
SetWindowPos(hwnd, IntPtr.Zero, (int)(OldPoint.X + Offset), (int)(OldPoint.Y + Offset), (int)rect.Width, (int)rect.Height, SWP_NOOWNERZORDER | SWP_NOZORDER);
//等待一定时间间隔后恢复原始位置
System.Threading.Thread.Sleep(ShakingInterval);
SetWindowPos(hwnd, IntPtr.Zero, (int)OldPoint.X, (int)OldPoint.Y, (int)rect.Width, (int)rect.Height, SWP_NOOWNERZORDER | SWP_NOZORDER);
System.Threading.Thread.Sleep(ShakingInterval);
//累加循环次数
ShakingTime++;
}
//恢复窗口原始位置
SetWindowPos(hwnd, IntPtr.Zero, (int)OldPoint.X, (int)OldPoint.Y, (int)rect.Width, (int)rect.Height, SWP_NOOWNERZORDER | SWP_NOZORDER);
}
[DllImport("user32.dll")]
private static extern bool GetWindowRect(IntPtr hwnd, ref Rect rectangle);
[DllImport("user32.dll")]
private static extern bool SetWindowPos(IntPtr hwnd, IntPtr hwndInsertAfter, int x, int y, int cx, int cy, uint uFlags);
private const uint SWP_NOOWNERZORDER = 0x0200;
private const uint SWP_NOZORDER = 0x0004;
private struct Rect
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:C#模拟MSN窗体抖动的实现代码 - Python技术站