在c#中使用C代码

时间:2010-05-14 06:26:17

标签: c#

当我用谷歌搜索找到改变窗口样式的方法时,我可以找到“C”语言的代码 我如何在我的c#应用程序中使用下面的代码段,以便我可以隐藏外部应用程序的标题栏?我之前没有用过“C”。

    //Finds a window by class name
[DllImport("USER32.DLL")]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

//Sets a window to be a child window of another window
[DllImport("USER32.DLL")]
public static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);

//Sets window attributes
[DllImport("USER32.DLL")]
public static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);

//Gets window attributes
[DllImport("USER32.DLL")]
public static extern int GetWindowLong(IntPtr hWnd, int nIndex);

//assorted constants needed
public static int GWL_STYLE = -16;
public static int WS_CHILD = 0x40000000; //child window
public static int WS_BORDER = 0x00800000; //window with border
public static int WS_DLGFRAME = 0x00400000; //window with double border but no title
public static int WS_CAPTION= WS_BORDER | WS_DLGFRAME; //window with a title bar

/*
 This function sets the parent of the window with class
 ClassClass to the form/control the method is in.
*/
public void Reparent()
{
//get handle of parent form (.net property)
IntPtr par = this.Handle;
//get handle of child form (win32)
IntPtr child = FindWindow("ClassClass", null);
//set parent of child form
SetParent(child, par);
//get current window style of child form
int style = GetWindowLong(child, GWL_STYLE);

//take current window style and remove WS_CAPTION from it
SetWindowLong(child, GWL_STYLE, (style & ~WS_CAPTION));
}

2 个答案:

答案 0 :(得分:2)

我不是P / Invoke exprert,但是看看:http://www.pinvoke.net/default.aspx/coredll/SetWindowLong.html我想你可以调用SetWindowLong来改变窗口样式而不重复。

对于窗口搜索,您可以尝试:

Process[] processes = Process.GetProcessesByName("notepad.exe");
foreach (Process p in processes)
{
    IntPtr pFoundWindow = p.MainWindowHandle;
    // now you have the window handle
}

答案 1 :(得分:1)

您发布的代码段位于C#中,而不是C中。您应该只需将该代码添加到表单中并调用Reparent方法即可。 (假设您使用的是WinForms

请注意,Reparent方法不仅会更改窗口样式,还会尝试将窗口作为窗口的子窗口显示。