使用C#和WIN32滚动记事本

本文关键字:滚动 记事本 WIN32 使用 | 更新日期: 2023-09-27 18:24:50

我正在尝试使用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);
    }

使用C#和WIN32滚动记事本

此操作失败,因为您正在向主窗口发送WM_VSCROLL消息。您需要将消息发送到记事本的编辑控件,即带有滚动条的窗口。

您可以使用EnumChildWindows枚举记事本的子窗口。类为"Edit"的子项就是您想要的。