您的位置:首页 > 编程语言 > C#

C#操作移动其他程序窗口

2014-04-11 21:13 369 查看


在做项目时候,曾经遇到一个问题,就是用C#的WinForm,来打开一个使用C++编写的软件,并控制打开窗体位置和大小。

在这里使用了Win32 API来做的。可以使用C#根据窗体的路径,启动一个进程,然后使用Win32 API控制打开窗口的位置和大小。

主要代码如下:

public class A

{

//调用Win32 API

[System.Runtime.InteropServices.DllImportAttribute("user32.dll", EntryPoint = "MoveWindow")]

public static extern bool MoveWindow(System.IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);

//打开窗体方法,fileName是C++的窗体名称,包含路径

private void OpenAndSetWindow(String fileName)

{

Process p = new Process();//新建进程

p.StartInfo.FileName = fileName;//设置进程名字

p.StartInfo.CreateNoWindow = true;

p.StartInfo.WindowStyle = ProcessWindowStyle.Normal;

p.Start();

MoveWindow(p.MainWindowHandle, 200, 300, 500, 400, true);

//p.MainWindowHandle是你要移动的窗口的句柄;200,300是移动后窗口左上角的横纵坐标;500,400是移动后窗口的宽度和高度;true表示移动后的窗口是需要重画

}

}

如果打开IE网页,可以成下面语句一句

p.StartInfo.FileName = "iexplore";

p.StartInfo.Arguments = "www.baidu.com";//网页


C#可调用API接口来获取窗口句柄,发送消息控制其余程序窗体大小

根据标题获取窗口句柄

using System;
  using System.Runtime.InteropServices;
  namespace tstfindwindow
  {
  ///
  /// Class1 的摘要说明。
  ///
  class Class1
  {
  [DllImport( "User32.dll ")]
  public static extern System. IntPtr FindWindowEx(System. IntPtr parent, System. IntPtr childe, string strclass, string strname);
  ///
  /// 应用程序的主入口点。
  ///
  [STAThread]
  static void Main(string[] args)
  {
  //
  //TODO: 在此处添加代码以启动应用程序
  //
  IntPtr p=FindWindowEx(System.IntPtr.Zero,System.IntPtr.Zero,null,"窗口标题");
  }
  }


发送消息控制最大、最小

[DllImport("user32.dll", EntryPoint = "PostMessage")]
public static extern int PostMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
public const int WM_SYSCOMMAND = 0x112;
public const int SC_MINIMIZE = 0xF020;
public const int SC_MAXIMIZE = 0xF030;
private void button1_Click(object sender, EventArgs e)
{
PostMessage(Handle, WM_SYSCOMMAND, SC_MINIMIZE, 0);
}


分类: winform C#
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: