You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

寻求跨平台获取屏幕像素尺寸的Perl实现方案

跨平台获取屏幕像素尺寸(无需加载Perl/Tk)

你当前用Perl/Tk获取屏幕尺寸的代码是:

use Tk;
my $mw = MainWindow->new;
my $screen_width  = $mw->screenwidth();   
my $screen_height = $mw->screenheight();  

但不想依赖整个Tk库,以下是几种跨平台实现方案,都能返回和Tk一致的像素级屏幕尺寸:

方案1:使用轻量跨平台模块 Display::Resolution

这个模块专门用于获取显示分辨率,支持Windows、Linux、macOS,依赖少且加载轻量。

安装方式:

cpanm Display::Resolution

使用代码:

use Display::Resolution;
my ($width, $height) = get_resolution();
print "屏幕尺寸:${width}x${height}\n";

方案2:手动封装跨平台原生逻辑

如果不想额外安装模块,可以针对不同系统调用原生接口,避免冗余依赖:

sub get_screen_size {
    if ($^O eq 'MSWin32') {
        require Win32::API;
        Win32::API->Import('user32', 'GetSystemMetrics', 'N', 'N');
        my $width = Win32::API->Call(0);  # SM_CXSCREEN
        my $height = Win32::API->Call(1); # SM_CYSCREEN
        return ($width, $height);
    }
    elsif ($^O eq 'linux') {
        require X11::Xlib;
        my $display = X11::Xlib->new();
        my $width = $display->screen_width;
        my $height = $display->screen_height;
        $display->close;
        return ($width, $height);
    }
    elsif ($^O eq 'darwin') {
        require Mac::AppleScript;
        my $script = 'tell application "Finder" to get bounds of window of desktop';
        my ($bounds) = Mac::AppleScript::RunAppleScript($script);
        my (undef, undef, $width, $height) = split /,/, $bounds;
        return ($width, $height);
    }
    else {
        die "不支持的操作系统:$^O";
    }
}

# 使用示例
my ($screen_width, $screen_height) = get_screen_size();
print "屏幕宽:$screen_width,高:$screen_height\n";

各平台依赖说明:

  • Windows:需安装Win32::API模块
  • Linux:需安装X11::Xlib模块(远轻于完整Tk库)
  • macOS:需安装Mac::AppleScript模块

方案3:使用SDL多媒体库

SDL是跨平台多媒体库,加载后可快速获取屏幕尺寸,整体开销比Tk小:

安装方式:

cpanm SDL

使用代码:

use SDL;
use SDL::Video;

SDL::init(SDL_INIT_VIDEO);
my $display = SDL::Video::get_video_info();
my $screen_width = $display->current_w;
my $screen_height = $display->current_h;
SDL::quit();

print "屏幕尺寸:${screen_width}x${screen_height}\n";

以上方案都能实现不依赖Perl/Tk的跨平台屏幕尺寸获取,返回结果和Tk的screenwidth()/screenheight()完全一致。

内容的提问来源于stack exchange,提问作者Joseph Brenner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 22:01:16