簡體   English   中英

C#屏幕大小,無交互式參考

[英]C# Screen size without references in interactive

我想獲取主屏幕的屏幕尺寸,而不添加任何引用(例如WinFormsPresentation )。 我在這里找到了類似的問題,但是沒有解決方案不包括下載或類似的東西。

但是我想制作一個方法,該方法可以在其他任何PC上的C# 交互中執行。 因此,我需要一個不引用標准以外其他內容的解決方案(例如,允許使用SystemSystem.Core ,...)。

我知道這是可能的

System.Windows.Forms.Screen.PrimaryScreen.Bounds;

但這需要System.Windows.Forms引用,因此它不適合我。 但基本上,此代碼片段的結果是我希望在沒有引用的情況下獲得。

這是我想出的一個例子。

我注意到它在高DPI屏幕上無法正常工作。 它將報告表觀分辨率,而不是實際分辨率。

    static void Main(string[] args)
    {
        var size = GetScreenSize();
        Console.WriteLine(size.Length + " x " + size.Width);
        Console.ReadLine();
    }

    static Size GetScreenSize()
    {
        return new Size(GetSystemMetrics(0), GetSystemMetrics(1));
    }

    struct Size
    {
        public Size(int l, int w)
        {
            Length = l;
            Width = w;
        }

        public int Length { get; set; }
        public int Width { get; set; }
    }

    [DllImport("User32.dll", ExactSpelling = true, CharSet = CharSet.Auto)]
    public static extern int GetSystemMetrics(int nIndex);

如果您不想使用這些庫,則可能需要使用本機方法。 我想不出解決辦法,因為您需要以任何方式與系統進行通信。

一個很好的起點是System.Windows.Forms.Screen的源代碼

這是到源的鏈接 我敢打賭,您可以剝離他們的代碼,並獲得最低限度的價格。

我實際上找到了解決方案:

using System;
using System.Runtime.InteropServices;
static void Main()
{
    EnumWindows(E, IntPtr.Zero);
    Console.Write($"{_.Item1}x{_.Item2}");
}


struct R
{
    int l;
    int t;
    public int r;
    public int b;

    public override string ToString() => $"{l},{t},{r},{b}";
    public bool i() => l == 0 && r != 00;
}

static (int, int) _;

static bool E(IntPtr w, IntPtr l)
{
    var r = new R();
    GetWindowRect(w, ref r);
    if (r.i() && _.Item1 == 0)
        _ = (r.r, r.b);
    return true;
}

delegate bool P(IntPtr w, IntPtr l);

[DllImport("user32.dll")]
static extern bool EnumWindows(P e, IntPtr l);

[DllImport("user32.dll")]
static extern bool GetWindowRect(IntPtr w, ref R r);
Main()

將此粘貼到您的交互式文件中,它將輸出屏幕分辨率-至少對我有用。

不要問我它是如何工作的,它來自不同的教程,並被壓入了交互中。 因此,我不能保證這將適用於每台PC。

可以請其他人測試一下嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM