0

我正在尝试在 C# 中对外部窗口进行子类化。我以前在 VB6 中使用过类似的东西,没有任何问题,但是下面的代码不起作用。有人可以帮帮我吗?

//API

[DllImport("user32")]
private static extern IntPtr SetWindowLong(IntPtr hWnd, int nIndex, IntPtr newProc);

[DllImport("user32")]
private static extern IntPtr SetWindowLong(IntPtr hWnd, int nIndex, WinProc newProc);

[DllImport("user32.dll")]
private static extern IntPtr DefWindowProc(IntPtr hWnd, int uMsg, int wParam, int lParam);

[DllImport("user32")]
private static extern IntPtr CallWindowProc(IntPtr lpPrevWndFunc, IntPtr hWnd, int Msg, int wParam, int lParam);

private delegate IntPtr WinProc(IntPtr hWnd, int Msg, int wParam, int lParam);

private const int GWL_WNDPROC = -4;

private enum winMessage : int
{
    WM_GETMINMAXINFO = 0x024,
    WM_ENTERSIZEMOVE = 0x231,
    WM_EXITSIZEMOVE = 0x232
}

private WinProc newWndProc = null;
private IntPtr oldWndProc = IntPtr.Zero;
private IntPtr winHook = IntPtr.Zero;

//Implementation

public void hookWindow(IntPtr winHandle)
{
    if (winHandle != IntPtr.Zero)
    {
        winHook = winHandle;

        newWndProc = new WinProc(newWindowProc);
        oldWndProc = SetWindowLong(winHook, GWL_WNDPROC,newWndProc);
    }
}

public void unHookWindow()
{
    if (winHook != IntPtr.Zero)
    {
        SetWindowLong(winHook, GWL_WNDPROC, oldWndProc);
        winHook = IntPtr.Zero;
    }
}

private IntPtr newWindowProc(IntPtr hWnd, int Msg, int wParam, int lParam)
{
     switch (Msg)
     {
         case (int)winMessage.WM_GETMINMAXINFO:
             MessageBox.Show("Moving");
             return DefWindowProc(hWnd, Msg, wParam, lParam);

}
4

2 回答 2

3

好的,我完成了编码,但是在您的解决方案中,您必须拥有表单解决方案和 dll 解决方案,并且它可以工作,如果您想要该代码,请告诉我。但您不能在同一个 exe 中进行子类化。所以这一切都可以在 c# 中完成,但是当我开始转换我的 c++ 项目时,你确实需要那个 dll

都是因为

BOOL WINAPI DllMain(HANDLE hinstDLL, DWORD fdwReason, LPVOID lpvReserved )
{
    switch(fdwReason)
    {
        case DLL_PROCESS_ATTACH:
            {
                hInstance=(HINSTANCE)hinstDLL;
            }
            break;
        case DLL_PROCESS_DETACH:
            {
                if((int)hndll>1)
                {
                    SetWindowLong(hndll,GWL_WNDPROC,OldWndHndl);   //Set back the old window procedure
                    return 1;
                }       
            }
    }
}
于 2011-08-15T19:48:17.887 回答
0

用 C# 是不可能的。只有非托管 C/C++ 才能做到这一点。

oldWndProc = SetWindowLong(winHook, GWL_WNDPROC,newWndProc);如果 winHook 来自另一个进程,将始终返回 0(表示失败)。

参考:https ://social.msdn.microsoft.com/Forums/vstudio/en-US/8dd657b5-647b-443b-822d-ebe03ca4033c/change-wndproc-of-another-process-in-c

于 2014-12-15T14:20:42.683 回答