如何解决word窗口中的相对坐标转化为屏幕坐标

正 唐 0 信誉分
2025-02-09T05:08:33.6066667+00:00

我在编写我的C#程序,试图完成一个对word窗口操作的winForm时遇到了问题。我无法将一个给定的range在窗口中的坐标转化为在屏幕里的坐标,来让我子窗口加以显示

Word
Word
Microsoft 文字处理软件产品系列,用于创建 Web、电子邮件和打印文档。
42 个问题
C#
C#
一种面向对象的类型安全的编程语言,它起源于 C 语言系列,包括对面向组件的编程的支持。
210 个问题
0 个注释 无注释
{count} 票

2 个答案

排序依据: 非常有帮助
  1. Emi Zhang-MSFT 28,746 信誉分 Microsoft 外部员工
    2025-02-10T03:39:17.08+00:00

    你好,

    你可以使用PointToClientPointToScreen方法在屏幕坐标和客户端坐标之间进行转换。

    // 获取Word文档中的Range对象
    Word.Range range = ...;
    // 获取Range对象的屏幕坐标
    Word.Window window = range.Application.ActiveWindow;
    Word.PointsToScreen(range, out int x, out int y);
    // 将屏幕坐标转换为客户端坐标
    Point screenPoint = new Point(x, y);
    Point clientPoint = this.PointToClient(screenPoint);
    // 在子窗口中显示
    Form childForm = new Form();
    childForm.StartPosition = FormStartPosition.Manual;
    childForm.Location = clientPoint;
    childForm.Show();
    

    希望这些信息对你有所帮助。


  2. Emi Zhang-MSFT 28,746 信誉分 Microsoft 外部员工
    2025-02-17T01:26:23.03+00:00

    你可以使用Windows API来获取窗口的相关信息。

    using System;
    using System.Runtime.InteropServices;
    using System.Diagnostics;
    
    class Program
    {
        [DllImport("user32.dll")]
        private static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);
    
        [DllImport("user32.dll")]
        private static extern bool GetClientRect(IntPtr hWnd, out RECT lpRect);
    
        [DllImport("user32.dll")]
        private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
    
        [StructLayout(LayoutKind.Sequential)]
        private struct RECT
        {
            public int Left;
            public int Top;
            public int Right;
            public int Bottom;
        }
    
        static void Main()
        {
            // 找到Word窗口句柄
            IntPtr hWnd = FindWindow("OpusApp", null);
            if (hWnd == IntPtr.Zero)
            {
                Console.WriteLine("未找到Word窗口");
                return;
            }
    
            // 获取窗口矩形
            GetWindowRect(hWnd, out RECT windowRect);
            // 获取客户区矩形
            GetClientRect(hWnd, out RECT clientRect);
    
            // 计算标题栏和菜单栏的高度
            int titleBarHeight = (windowRect.Bottom - windowRect.Top) - (clientRect.Bottom - clientRect.Top);
    
            Console.WriteLine($"标题栏和菜单栏的高度: {titleBarHeight} 像素");
        }
    }
    
    

    请尝试一下。

    0 个注释 无注释

你的答案

问题作者可以将答案标记为“接受的答案”,这有助于用户了解已解决作者问题的答案。