using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using Microsoft.Win32;namespace 活动窗体震动
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} internal struct RECT //Win32汇编数据结构不用自己定义
{
public int left;
public int top;
public int right;
public int bottom;
} [DllImport("user32.dll", ExactSpelling = true, SetLastError = true)]
internal static extern IntPtr GetForegroundWindow(); [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall, ExactSpelling = true, SetLastError = true)]
internal static extern RECT GetWindowRect(IntPtr hwnd); [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall, ExactSpelling = true, SetLastError = true)]
internal static extern void MoveWindow(IntPtr hwnd,int X,int Y,int nWidth,int nHeight,bool bRepaint);
IntPtr id;
private void timer1_Tick(object sender, EventArgs e)
{
id = GetForegroundWindow();
Random myRandom = new Random();
RECT Rect = GetWindowRect(id);
MoveWindow(id, myRandom.Next(1024), myRandom.Next(768), Rect.right-Rect.left, Rect.bottom-Rect.top, true);
}
}
}跟踪发现Rect.right-Rect.left,Rect.bottom-Rect.top算出来居然是4,4我的顶层窗体少说也有(100,60)大小了.我原来用Win32汇编成功过,不过RECT这些数据结构不用自己定义.
解决方案 »
- 检索 COM 类工厂中 CLSID 为 {79AD7B73-C515-40B4-8B02-CB0F5FA5A1A8} 的组件时失败
- winform 焦点事件
- C#反射对象设置属性时的问题
- 关于WinForm的
- C#连接数据库SqlConnection.ConnectionString 属性“Server=(local)”没用
- 无刷新联动取不到值的 问题
- 关于排序的一些问题!!!!!!!!!
- C#如何在互联网中传共亨数据文件
- 如何把这个转换成C#?
- 请问后台添加GridView如何分页
- 获取 datagrid 行列值,以及列名称
- DataGridViewComboBoxColumn在DataGridView新增时的问题。
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
internal static extern bool GetWindowRect(IntPtr hWnd, ref RECT rect);2:你使用GetForegroundWindow获取不一定是你设置的窗口,而是指最上一次用户正使用的窗口。觉得你应该使用如下的属性:
Form.Handle改了下你的代码并运行通过:
internal struct RECT //Win32汇编数据结构不用自己定义
{
public int left;
public int top;
public int right;
public int bottom;
}[DllImport("user32.dll", ExactSpelling = true, SetLastError = true)]
internal static extern IntPtr GetForegroundWindow();[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
internal static extern bool GetWindowRect(IntPtr hWnd, ref RECT rect);[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall, ExactSpelling = true, SetLastError = true)]
internal static extern void MoveWindow(IntPtr hwnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);
IntPtr id;
private void timer1_Tick(object sender, EventArgs e)
{
//id = GetForegroundWindow();
id = this.Handle; RECT Rect=new RECT();
Random myRandom = new Random();
GetWindowRect(id, ref Rect);
MoveWindow(id, myRandom.Next(1024), myRandom.Next(768), Rect.right - Rect.left, Rect.bottom - Rect.top, true);
}