日期:2014-05-18  浏览次数:20847 次

我的GetWindowRect怎么失灵了
C# code

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这些数据结构不用自己定义.

------解决方案--------------------

------解决方案--------------------
你要实现什么?
------解决方案--------------------
1:你使用的GetWindowRect方法说实话没有见过,我觉得应该使用如下的方法:

C# code

[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
internal static extern bool GetWindowRect(IntPtr hWnd, ref RECT rect);

------解决方案--------------------
个人觉得你的程序稍带有一定的“有害”性,如果不小心,我们的机子会被你的代码搞的乱了套!