myamanda

博客园 首页 新随笔 联系 订阅 管理

因显示器的分辩率的不一致而影响软件界面及人机正常交互的情形太多了。通常,我们的应用可能用VB、Delphi、PB等不同语言实现的,如果在各种语言中都调用API来实现动态的变屏幕设置的话,先不管调用能否成功,光一个DEVMODE结构在不同语言的定义就需要半天。能不能自己做一个DLL,装封几个简单的动态改变屏幕分辨率的函数,以达到不同语言均可调用的目的呢?作者进行了一番探索。Delphi语言封装大部分Windows API函数,只要在uses子句后加上 Windows,即可直接调用许多Windows API函数。因此笔者选用Delphi语言。

---- 一、 创建一个DLL

---- 关于在Delphi中如何创建DLL,已有不少文章介绍过了,读者也可以在Delphi5.0的帮助中查找(有详细例子),在此不再赘述。Setscn.dll中装封了三个函数:

---- setdisplaymode函数实现动态设置屏幕分辩率,参数pwidth、pheight为欲设置分辩率的屏宽和屏高,返回值为longint型,为0表示成功。

---- getscreenwidth()函数的功能是取得当前屏幕的屏宽,返回值为longint型。

---- getscreenwidth()函数的功能是取得当前屏幕的屏高,返回值为longint型。

---- 程序源代码如下:

library  setscn;
uses Windows;
var NewDevMode: TDEVMODE;
function setdisplaymode(pwidth,pheight:integer):
longint;stdcall;export;
begin
With NewDevMode do
begin
dmSize := 122;
dmFields := DM_PELSWIDTH Or DM_PELSHEIGHT ;
dmPelsWidth := pwidth ;
dmPelsHeight := pheight ;
end;
result:=ChangeDisplaySettings(NewDevMode,0);
end;
Function getscreenwidth():longint;stdcall;export;
begin
result:=GetDeviceCaps(hinstance, HORZRES);
end;
function getscreenheight():longint;stdcall;export;
begin
result:=GetDeviceCaps(hinstance, VERTSIZE);
end;
exports
setdisplaymode index 1,
getscreenwidth index 2,
getscreenheight index 3;
begin
end.
---- 编译以上代码,生成一个名为setscn.dll的动态连接库,将其拷贝到windows的system目录下,便大功告成。

---- 二、 为setscn创建引入程序单元

---- 为了在Delphi语言中成功调用上述函数,我们需要编写以下引入程序单元。

{Import unit for setscn.Dll}
unit scnimport;
interface
function setdisplaymode(pwidth,pheight:integer):longint;
function getscreenwidth():longint;
function getscreenheight():longint;
implementation
function setdisplaymode(pwidth,pheight:integer):longint;
external 'setscn' index 1;
function getscreenwidth():longint;external 'setscn' index 2;
function getscreenheight():longint;external 'setscn' index 3;
end.
---- 三、 不同语言中的声明及调用:

---- 1、 VB中声明及调用:

---- VB中声明:

Private Declare Function setdisplaymode Lib 
"setscn.dll" (ByVal pwidth As Integer, ByVal
pheight As Integer) As Long
Private Declare Function getscreenwidth Lib
"setscn.dll" () As Long
Private Declare Function getscreenheight Lib
"setscn.dll" () As Long
Dim sh, sw As Long
---- 调用示例:点击Command1将屏幕分辩率设为640*480,点击Command2恢复原来设置。
Private Sub Command1_Click()
sw = getscreenwidth()
sh = getscreenheight()
setdisplaymode 640, 480
End Sub
Private Sub Command2_Click()
setdisplaymode sw, sh
End Sub
---- 2、PB中声明及调用:

---- PB中声明:

Public Function long setdisplaymode(long pwidth, 
long pheight)Library " setscn.dll"
Public Function long getscreenwidth()Library
" setscn.dll"
Public Function long getscreenheight()Library
" setscn.dll"
---- 调用示例:点击cb_1将屏幕分辩率设为640*480,点击cb_2恢复原来设置。如下:
//clicked for cb_1 return long
//sw、sh是long型的全程变量
sw=getscreenwidth()
sh=getscreenheight()
setdisplaymode(640,480)
//clicked for cb_2 return long
setdisplaymode(sw,sh)
---- 3、Delphi中的声名及调用

---- 因为我们为setscn创建引入程序单元scnimport.pas,所以只要在uses子句后添加上scnimport,即可直接调用(源代码略)。

posted on 2009-11-25 14:03  myamanda  阅读(301)  评论(0)    收藏  举报