如何在应用程序外更改表单的窗口样式?

时间:2009-12-13 11:59:03

标签: c# .net windows handles

如何更改应用程序外的表单窗口样式?难题?
我实际上试图移动一个女巫最顶层的形式,没有边框 我有窗口的手柄(hWnd) 如果保证可以工作,我可以编写数千行代码。

1 个答案:

答案 0 :(得分:3)

假设这个窗口可以来自任何类型的基于Win32的运行时生成的任何应用程序,看起来你不得不求助于p / invoke核心Win32 apis进行窗口操作。

例如,您可以使用SetWindowPos,可以从user32.dll导入。这是签名:

BOOL SetWindowPos(HWND hWnd, 
  HWND hWndInsertAfter,
  int X,
  int Y,
  int cx,
  int cy,
  UINT uFlags
);

我不会假设您之前已经完成了p / invoke导入,所以让我们从顶部开始。让我们抨击一个Windows窗体应用程序:

1)创建一个Windows窗体应用程序,然后将这些声明添加到Form1类:

/* hWndInsertAfter constants.  Lifted from WinUser.h, 
 * lines 4189 onwards depending on Platform SDK version */
public static IntPtr HWND_TOP = (IntPtr)0;
public static IntPtr HWND_BOTTOM = (IntPtr)1;
public static IntPtr HWND_TOPMOST = (IntPtr)(-1);
public static IntPtr HWND_NOTOPMOST = (IntPtr)(-2);

/* uFlags constants.  Lifted again from WinUser.h, 
 * lines 4168 onwards depending on Platform SDK version */
/* these can be |'d together to combine behaviours */
public const int SWP_NOSIZE          = 0x0001;
public const int SWP_NOMOVE          = 0x0002;
public const int SWP_NOZORDER        = 0x0004;
public const int SWP_NOREDRAW        = 0x0008;
public const int SWP_NOACTIVATE      = 0x0010;
public const int SWP_FRAMECHANGED    = 0x0020;
public const int SWP_SHOWWINDOW      = 0x0040;
public const int SWP_HIDEWINDOW      = 0x0080;
public const int SWP_NOCOPYBITS      = 0x0100;
public const int SWP_NOOWNERZORDER   = 0x0200;  /* Don't do owner Z ordering */
public const int SWP_NOSENDCHANGING  = 0x0400;  /* Don't send WM_WINDOWPOSCHANGING */
public const int SWP_DRAWFRAME       = SWP_FRAMECHANGED;
public const int SWP_NOREPOSITION    = SWP_NOOWNERZORDER;
public const int SWP_DEFERERASE      = 0x2000;
public const int SWP_ASYNCWINDOWPOS  = 0x4000;

[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern int SetWindowsPos(IntPtr hWnd,
  IntPtr hWndInsertAfter,
  int x,
  int y,
  int cx,
  int cy,
  UInt32 uFlags);

使用Win / Windows窗口方法进行p /调用时,烦人的事情是你必须开始导入Win32使用的各种数字常量等 - 因此事先都是gumph。

请参阅SetWindowPos方法的MSDN链接,了解它们的用途。

2)在名为cmdMakeHidden的表单中添加一个按钮,然后按如下方式编写处理程序:

private void cmdMakeHidden_Click(object sender, EventArgs e)
{
  //also causes the icon in the start bar to disappear
  //SWP_HIDEWINDOW is the 'kill -9' of the windows world without actually killing!
  SetWindowPos(this.Handle, HWND_TOP, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE | SWP_HIDEWINDOW);
}

用您选择的窗口句柄替换'this.Handle'以隐藏该窗口。

此方法实际上用于一次应用多个更改,因此需要使用某些SWP_NO*选项。例如,您应指定SWP_NOSIZE,否则为cx和cy传递0将导致窗口同时缩小到零宽度和高度。

要演示移动窗口,请在表单中添加另一个名为cmdMove的按钮,然后按如下所示编写单击处理程序:

private void cmdMove_Click(object sender, EventArgs e)
{
  SetWindowPos(this.Handle, HWND_TOP, 100, 100, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOREPOSITION);
}

只要按下按钮,此代码就会将表单移动到100,100。

再次,根据您的需要更换this.Handle。此处的HWND_TOP是完全可选的,因为已使用SWP_NOZORDER和SWP_NOREPOSITION标志禁用了重新排序。

希望这有助于您走上正确的轨道!