使用C#和WIN32滚动记事本

时间:2012-02-15 20:14:44

标签: c# .net windows winapi

我正在尝试使用C#应用程序滚动记事本窗口。下面是相关的代码块,移动/调整窗口的调用是有效的,所以我知道句柄是有效的

请你看看我错过了什么,当它运行时没有任何反应。

    [Flags]
    public enum SetWindowPosFlags : uint
    {
        SWP_ASYNCWINDOWPOS = 0x4000,
        SWP_DEFERERASE = 0x2000,
        SWP_DRAWFRAME = 0x0020,
        SWP_FRAMECHANGED = 0x0020,
        SWP_HIDEWINDOW = 0x0080,
        SWP_NOACTIVATE = 0x0010,
        SWP_NOCOPYBITS = 0x0100,
        SWP_NOMOVE = 0x0002,
        SWP_NOOWNERZORDER = 0x0200,
        SWP_NOREDRAW = 0x0008,
        SWP_NOREPOSITION = 0x0200,
        SWP_NOSENDCHANGING = 0x0400,
        SWP_NOSIZE = 0x0001,
        SWP_NOZORDER = 0x0004,
        SWP_SHOWWINDOW = 0x0040,
    }


    private const int WM_SCROLL = 276; // Horizontal scroll
    private const int WM_VSCROLL = 277; // Vertical scroll
    private const int SB_LINEUP = 0; // Scrolls one line up
    private const int SB_LINELEFT = 0;// Scrolls one cell left
    private const int SB_LINEDOWN = 1; // Scrolls one line down
    private const int SB_LINERIGHT = 1;// Scrolls one cell right
    private const int SB_PAGEUP = 2; // Scrolls one page up
    private const int SB_PAGELEFT = 2;// Scrolls one page left
    private const int SB_PAGEDOWN = 3; // Scrolls one page down
    private const int SB_PAGERIGTH = 3; // Scrolls one page right
    private const int SB_PAGETOP = 6; // Scrolls to the upper left
    private const int SB_LEFT = 6; // Scrolls to the left
    private const int SB_PAGEBOTTOM = 7; // Scrolls to the upper right
    private const int SB_RIGHT = 7; // Scrolls to the right
    private const int SB_ENDSCROLL = 8; // Ends scroll


    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    private static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);

    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, SetWindowPosFlags uFlags);



    public void scroll()
    {


        IntPtr handle = IntPtr.Zero;

        Process[] processes = Process.GetProcessesByName("Notepad");

        foreach (Process p in processes)
        {
            handle = p.MainWindowHandle;

            Console.WriteLine("Got Handle: " + p.MainWindowTitle);

            break;
        }

        //this is to test I have a valid handle
        SetWindowPos(handle, new IntPtr(0), 10, 10, 1024, 350, SetWindowPosFlags.SWP_DRAWFRAME);


        SendMessage(handle, WM_VSCROLL,  (IntPtr)SB_LINEDOWN, IntPtr.Zero);
        SendMessage(handle, WM_VSCROLL, (IntPtr)SB_PAGEDOWN, IntPtr.Zero);

    }

1 个答案:

答案 0 :(得分:4)

这会失败,因为您正在将WM_VSCROLL消息发送到主窗口。您需要将消息发送到记事本的编辑控件,该控件是带滚动条的窗口。

您可以使用EnumChildWindows枚举记事本的子窗口。具有“编辑”类的孩子就是你想要的孩子。