PowerBuilder技巧

1.RGB函数计算公式: 颜色值 = (65536 * Blue) + (256 * Green) + (Red)

2.控件可拖动:
send(handle(this),274,61458,0)

3.如何用程序控制下拉子数据窗口的下拉和收起
用modify或者直接用dw_1.object.col1.dddw.showlist = true

4.检索参数有些不需要传入则传%.

5.如何屏蔽鼠标滚轮触发
在控件的other事件写
if message.number = 522 then return 1

6.得到数据窗口的语法:
string ls_dwsyntax
ls_dwsyntax=dw_1.describe("datawindow.syntax")

7.得到数据窗口中各列及标题:
long ll_count,i
string ls_value,ls_colname

ll_colnum = Long(dw_1.object.datawindow.column.count)

for i = 1 to ll_colnum
//得到标题头的名字
ls_colname = dw_1.describe('#' + string(i) + ".name") + "_t"
ls_value = dw_1.describe(ls_colname + ".text")
next

8.在程序中动态设置初始值:
ex:dw_contro.object.columnName.initial = 'xxxx'

9.如何在DataWindow的SQL语法中不使用SELECT DISTINCT实现删除重复的行

---- 起先对你要显示唯一值的列进行排序:"city A",然后增加如下过滤字符串:" city < > city [-1] or GetRow () = 1"

10.如何改变列的字体颜色,提醒用户此列已做修改

---- 在列的Color属性中,输入如下表达式IF (column_name < >column_name.Original, RGB(255, 0, 0), RGB(0, 0, 0))。在这个条件中,如果此列已改变,则显示红色字体,否则显示黑色字体。这个表达式主要用column_name < > column_name.Original比较当前列的值和原始列的值是否相同来达到判断的目的。

11.在数据窗口的clicked或doubleclicked事件中写上注释//可解决一些意外的bug!

12.如何屏蔽上下鍵触发
新建一个事件:id为pbm_dwnkey
IF KeyDown(KeyDownArrow!) OR KeyDown(KeyUpArrow!) Then
Return 1
End IF

13.你注意到没有,数据窗口画板里面,在写表达式的时候,试着用一些用户自定义的全局变量和全局函数,你会发现在某些特殊的场合,这个小窍门还是很有用的。

14.有些程序员在窗口的右键pop菜单里面写了很多代码,在菜单里面有很多w_windowname.controlname等等引用,如果这个窗口被继承,很容易就会出毛病,别忘了在菜单里面可以引用parentwindow哦,有了它我的pop菜单里面的代码和具体窗口无关,随便继承。当然强烈建议最好还是把所有和窗口相关的逻辑都转移到窗口的函数和事件中去,在pop菜单中触发调用。

15.whichdw.describe("evaluate('lookupdisplay("+colname+")',"+string(row)+")")

这个表达式可以得到指定列的显示值。(这个知识点有滥竽充数之嫌,但是一时间我真是想不起来太多的东西)

16.在数据窗口画板里面我们如果想要比较当前行和上一行或者下一行的值,怎么比较呢,哈哈,看这个就知道了

if ( yw_bc_circuit_dlcode = yw_bc_circuit_dlc

ode [-1] and yw_bc_circuit_dlname = yw_bc_circuit_dlname [-1] and yw_bc_circuit_xtno = yw_bc_circuit_xtno [-1] ,0,1)

这个表达式就是比较当前行和上一行是否相同的。其他的依此类推就行了。

17.两个结构相同的数据窗口之间快速复制数据

dw_1.object.data = dw_2.object.data

18.根据条件改变记录颜色
if ( Mod(getrow(),2)=0,rgb(0,255,255),rgb(255,255,255)) //奇偶行不同色
if (currentRow()=getrow(),rgb(0,255,255),rgb(255,255,255)) //当前行不同色

19.使窗口总位于所有打开窗口的最上面
w_main.SetPosition(Topmost!)

20.取数据窗口中列的总数
string ls_count
ls_count = dw_1.describe("datawindow.column.count")



21.取数据窗口中可列新的表名。
string ls_table
ls_table = dw_1.describe("datawindow.updatetable.table")

22.取数据窗口对象中列的名称及类型
string ls_cols[],ls_types[]
int li_count,i
li_count = integer(ls_count)
for i = 1 to li_count

ls_cols[i] = dw_1.describe("#"+string(i)+".name")

ls_types[i] = dw_1.describe("#"+string(i)+".coltype")

next

23.Case( dealintype WHEN 0 THEN RGB(254,251,235) WHEN 2 THEN rgb(254,251,235) ELSE RGB(0,0,255))
写道字段的protect中不仅仅是颜色改变的问题看看

24.dw.Object.col[n] : 直接获得数据窗口的col列第n 行的数据。

25.在做数据窗口时,我们有时候希望能够多一些字段来作一些特殊的用处,但是在数据窗口中又不能乱加字段,因为已有的字段必须是数据库中有的或者是他们的组合,呵呵,大家不妨看看这个sql用产生什么样的数据窗口
select colname1,colname2,1,''
from tablename
是不是多出了两个字段阿,一个是字符串字段,一个是数字字段
别忘了要convert syntax 哦

26.清空数组
string a[],b[]
a[1] = '1';a[1] = '2';a[1] = '3'
a = b//即可以清空a

27.只允许修改第n行的name列:
dw_1.modify("name.protect = '1 ~t if((getrow()=n),0,1)'")

28.让run程序和主程序一起关闭:
function ulong findwindowA(...).."user32.dll"
function long setparent(..."user32.dll"
handle = findwindowA(nul,win_title)
setparent(handle,handle(w_main))

29.取得某一天以前或以后n天的函数RelativeDate(date, n)
例:
取得当天前10天的日期
RelativeDate(Today(),10)
取得当天后10天的日期
RelativeDate(Today(),-10)

30.不想做排序窗口?调用PB自身的好了。
string ls_null
SetNull(ls_null)
dw_1.SetSort(ls_null)
dw_1.Sort()

31.调用PB自身的过滤窗口:
dw_1.SetFilter(ls_null)
dw_1.Filter()

32.增量输入定位代码或名称记录位置:
定义一个窗口,放一个SLE_1,在它的MODIFY程序中写:
long ll_find
string value0
value0=sle_1.text
if not (isnull(sle_1.text) or sle_1.text='') then
if left(sle_1.text,1)='0' or integer(sle_1.text)<>0 then //输入的为代码
ll_find=jwl_dmxz.dw_1.find('dm like

"'+value0+'%"',1,jwl_dmxz.dw_1.rowcount())//jwl_dmxz为主窗口,dm为查询的字段名,这里是代码。
else //输入的为名称
ll_find=jwl_dmxz.dw_1.find('mc like "'+value0+'%"',1,jwl_dmxz.dw_1.rowcount())//
end if
if ll_find>0 then
jwl_dmxz.dw_1.scrolltorow(ll_find)
//为了避免首次目标记录为第一条,无法选中。
if ll_find=ll_find0 then
jwl_dmxz.dw_1.selectrow(ll_find,true)
elseif ll_find<>ll_find0 then
jwl_dmxz.dw_1.selectrow(ll_find,true)
jwl_dmxz.dw_1.selectrow(ll_find0,false)
ll_find0=ll_find
end if
end if
end if

33.然后在查询窗口中的TIMER事件中写:
timer(0.05)
sle_1.triggerevent(modified!)


34.判断计算器是否存在:
string is_fileExists
boolean is_Exists
is_fileExists='c:\windows\calc.exe'
is_Exists=fileExists(is_fileExists)
if is_Exists then
run("c:\windows\calc.exe")
else
messagebox("提示信息","本机的WINDOWS没有计算器!",stopsign!)
end if

35.得到硬盘序例号
String ls_Rootpath, ls_volumnename ,ls_return,softpath
GetCurrentDirectoryA(256,softpath)
softpath=left(softpath,2)
if softpath='C:' then
ls_Rootpath = 'D:' // 指定要得到序列号的硬盘,
// 一般情况都是C盘,除非你能保证用户存在其它逻辑盘或物理盘
else
ls_Rootpath = 'C:'
end if
ls_volumnename = Space(256) // 分配足够的空间,下同
Ulong lul_VolumeNameSize
lul_VolumeNameSize = 256
Ulong lul_VolumeSerialNumber, lul_MaximumComponentLength, lul_FileSystemFlags
lul_MaximumComponentLength = 256

String ls_FileSystemNameBuffer
ls_FileSystemNameBuffer = space(256)

Ulong lul_FileSystemNameSize
lul_FileSystemNameSize = 256

int i
long ls_num,ls_gnum,ls_dnum

i=GetVolumeInformation(ls_Rootpath, ls_volumnename, lul_VolumeNameSize, lul_VolumeSerialNumber, lul_MaximumComponentLength, lul_FileSystemFlags, ls_FileSystemNameBuffer, lul_FileSystemNameSize)

ls_return=string(lul_VolumeSerialNumber)

return ls_return






1.如何让存储文件目录的列,显示图片?
答:选择对应的column的display as picture属性为true



2、如何复制grid类型的所选择的行的数据到系统剪切板?

答:string ls_selected

ls_selected=dw_1.Object.DataWindow.Selected.Data

clipboard(ls_selected)

3、如何复制graph风格的datawindow中的图形到剪切板?

答:dw_1.clipbord("gr_1")

4、如何设置的DW底色?

在DW的editsource中改变color的值

5、如何将Grid风格改成自由格式?

在DW的editsource中将processing=1的1改为0

6、要新建一个表A但风格和现有表格B风格一样,怎么将A表快速设置成表B风格?

复制B表C,在C表的DW中的editsource中将表名和字段名改成A表的,即可

7、如何实现gird风格的datawindow的多栏表头?

答:添

加 text到header带区,并设置band属性为foreground保存,edit source 修改text的x和width属性表达式如下:

x="100~t integer(describe('firstcol.x')" width="100~tinteger(describe('lastcol.x')) - integer(describe('firstcol.x')) +integer(describe('lastcol.width'))

8、如何过滤dddw编辑风格的显示值为指定值的记录?

答:dw_1.setfilter("lookupdisplay('column_name')='"+ls_display_value_your+"'")

dw_1.filter()

9、如何设置datawindow的某一列为空?

答:string ls_temp[]

setnull(ls_temp)

dw_1. O B J E C T.columnname.primary.current=ls_temp

10、如何设置datawindow的单双行不同颜色间隔?

答:在detail带区的color属性表达式中写上if(mod(getrow(),2)=1 ,rgb(255,0,0),rgb(0,255,0)),如果是当前行以第三种颜色表示,表达式如下:if(getrow()=current(),rgb(255,0,0),if(mod(getrow(),2)=1 ,rgb(0,0,255),rgb(0,255,0)))

11、如何获取指定名称的datawindow O B J E C T?

答:DWObject ldwo_use,ldwo_abc
ldwo_use = dw_1.Object
ldwo_abc = ldwo_use.__get_attribute("t_1",FALSE)//t_1为datawindow中text对象的名称

12、如何使用datawindow的查询模式?

答:dw_1.Object.DataWindow.QueryMode='yes'将datawindow改变为查询模式后,接收用户的输入,再使用一下代码获取结果:

dw_1.accepttext()

dw_1.retrieve()

13、如何缩放datawindow的打印大小?

答:dw_1. O B J E C T.datawindow.zoom=150 or dw_1. O B J E C T.datawindow.zoom=75

14、如何在已过滤后的数据基础上对datawindow进行过滤?

答:dw_1.setfilter(dw_1.describe("datawindow.table.filter")+your_join+your_new_filter)

dw_1.filter()

15、如何在datawindow中显示动态时间?

答:建立一个计算域,表达式为string(datetime(today(),now()),'yyyy年mm月dd日 hh点mm分ss秒'),同时设置datawindow的属性dw_1.Object.DataWindow.Timer_Interval=500

16、如何让带用title bar的datawindow控件的标题栏诚活动窗口的颜色?

答:外部函数定义:

funcation logn SetActiveWindow(long hwnd ) Library "user32.dll"

datawindow控件的clicked事件代码:

setactivewindow(handle(this))

17、如何设置datawindow的当前行指示图标?

答:在datawindow中建立一个计算列,expression为'',并将该计算列移动为datawindow的第一个列,在datawindow控件的

rowfocuschanged事件中写入代码:

SetRowFocusIndicator(hand!)或setrowfucsindicator(p_1)//p_1为窗口上的picture控件名

18、如何通过代码打开dddw?

答:定义外部函数引用声明

SUBROUTINE keybd_event( int bVk, int bScan, int dwFlags, int dwExtraInfo) LIBRARY "user32.dll"

代码如下:
[constant integer VK_F4 = 115

dw_1.SetFocus()

dw_1.SetColumn( "dept_head_id" ) //设置当前dddw

keybd_event( VK_F4,0,0,0 ) // 按下F4键

keybd_event( VK_F4,0,2,

0 ) // 释放F4键

19、如何打印datawindow的内容到文件中?

答: dw_1. O B J E C T.datawindow.print.fileName ="c:\temp.prn"

dw_1.print()

20、如何设置dddw的初始值?

答:dw_1. O B J E C T.columnname.Initial="your_initial_value"

21、如何只显示不同的数据?

答:dw_1.filter("isnull(columnname[-1]) and columnname <>columnname[-1]")

dw_1.filter()

22、如何让带有title bar的datawindow不可以移动?

答:在datawindow的自定义事件ue_nchittest(pbm_nchittest)中写入如下代码:

return 1

23、如何在N-UP显示风格中建立基于第N栏中的列的计算列?

答:如column有两列,number和price ,并显示为两栏,则第一栏的cost计算列的expression为number*price,第二栏的cost_1计算列的expression为number[1]*price[1]

24、如何清空ddlb或edit.codetable中项目?

答:dw_1.Object.columnname.Values=""

25、如何实现指定的column的字体旋转90度?

答:dw_1. O B J E C T.columnname.font.Escapement ="900"

26、如何获取datawindow的sql代码?

答: 可以通过以下四种方法获取sql代码:

string szselect

szselect=dw_1.describe("datawindow.table.select")

szselect=dw_1.describe("datawindow.table.sqlselect")

szselect=dw_1.describe("datawindow.table.select.attribute")

szselect=dw_1.getsqlselect()

27、如何获取datawindow对象占有的虚拟存储的容量?

答:使用datawindow.storage属性

举例:在datawindow控件的retrieverow事件中,写如如下代码:

long lstorage

lstorage=long(dw_1. O B J E C T.datawindow.storage)

if lstorage>50000 then dbcancel()

28、如何控制打印横向:

dw_control. O B J E C T.datawindow.print.orientation= 1


29、如何进行预览:

dw_control. O B J E C T.datawindow.print.preview = "yes"

30、如何连续在同一张纸打印两个数据窗口?

答:dw_1. O B J E C T.datawindow.print.filename="temp.prn"

dw_2. O B J E C T.datawindow.print.filename="temp.prn"

dw_1.print()

dw_2.print()





31、如何将pb9.0 的datawindow转化为pb 8.0版本的datawindow?

答:edit source 将release 9;改为release 8;

并删除以下内容:

print.printername=""

print.canusedefaultprinter=yes

print.cliptext=no print.overrideprintjob=no

hidegrayline=no

encodeselflinkargs="1"

export.xml(headgroups="1" includewhitespace="0" metadatatype=0 savemetadata=0 )

import.xml()

export.pdf(method=0 distill.custompostscript="0" xslfop.print="0" )

32、如何设置datawindow分组后每个分组中的记录号?

答:建立一个计算列,expression为 getrow() - first(getrow() for group 1)+1

33、如何实现在datawindow中只有

新增的行,才可以编辑?

答:在所有的column的protect属性表达式中写入以下表达式:

if(isrownew(),'0','1')

34、保存datawindow数据到excel中

// ... Init docname
// ... GetFileOpenName or any other method

if dw_1.SaveAs(docname, HTMLTable!, True) = -1 then
MessageBox("Warning", "Unable to export data. Error writing to file!", Exclamation!)
return
end if


// Convert HTML file to Excel native format
OLEObject excel
excel = CREATE OLEObject
if excel.ConnectToObject(docname) = 0 then
excel.application.DisplayAlerts = FALSE
excel.application.workbooks(1).Parent.Windows(excel.application.workbooks(1).Name).Visible = True
excel.application.workbooks(1).saveas(docname, 39)
excel.application.workbooks(1).close()
end if

DESTROY excel
// done


35、除了循环以外,有没有更好的方法统计数据窗口中处于选中状态的行数?

一般习惯于使用循环来统计数据窗口中处于选中状态的行数,有没有更好的方法?

其实此问题在应用上用处不大,讨论一下,活跃一下思维还是有好处的。

方法一:
long ll_Selected

ll_Selected = long(dw_1.describe("evaluate('sum( if(IsSelected(), 1, 0) for all)',1)"))

方法二:
long ll_Selected

ll_Selected = long(dw_1.describe("evaluate('count(IsSelected() for all)',1)"))


方法三:

upperbound(dw_1.Object.Data.Selected)




36、问:怎么让PB只打印当前记录,是用Free格式制作的数据窗口!

答:
DataStore ldt_temp
long ll_Row , ll_Rows
ll_Rows = dw_XX.Rowcount()
If ll_Rows = 0 Then GoTo the_end
If ll_Rows = 1 Then
dw_XX.Print()
GoTo the_end
End if
dw_XX.SetRedraw(False)
ldt_temp = Create DataStore
ldt_temp.DataObject = dw_XX.DataObject
ll_Row = dw_XX.GetRow()
dw_XX.RowsMove(1 , ll_Rows , Primary! , ldt_temp , 1 , Primary!)
ldt_temp.RowsMove(ll_Row , ll_Row , Primary! , dw_XX , 1 , Primary!)
dw_XX.Print()
dw_XX.RowsMove(1 , 1 , Primary! , ldt_temp , ll_Row , Primary!)
ldt_temp.RowsMove(1 , ll_Rows , Primary! , dw_XX , 1 , Primary!)
Destroy ldt_temp
dw_XX.SetRedraw(True)
the_end:
//只用将上述脚本拷入到打印部分即可,dw_XX为被打印的free型数据窗口,该方法可保证dw_XX中的数据在打印前后包括sort等属性均不发生任何改变,但效率较低,不宜用在数据量太大的数据窗口中,当然,考虑到打印本身速度就比较慢,所以3000行数据是可以采用这种方法并让用户接受的。若在同一窗口上存在与dw_XX共享的grid数据窗口并且与dw_XX同时显示,则需要与dw_one一起SetRedraw()




37、怎样将数据窗口(free格式)中的内容转

成word文档

答:给你两个函数:
(1)、辅助函数
$PBExportHeader$f_cncharnum.srf
$PBExportComments$得到字符串中汉字或者双字节的个数
global type f_cncharnum from function_ O B J E C T
end type

forward prototypes
global function integer f_cncharnum (string aString)
end prototypes

global function integer f_cncharnum (string aString);
//函数名: f_cncharnum
//用途: 返回一个字符串中汉字的个数
//输入: aString - string, 给定的字符串
//返回值: li_num - Integer, 给定的字符串中汉字的个数
//注意: 1. 此方法基于汉字的国标汉字库区位编码的有效性,不符合此编码的系统此函数无效!
// 2. 若汉字串含有非汉字字符,如图形符号或ASCII码,则这些非汉字字符将保持不变.
//例如: li_ret = f_cncharnum("摆渡人ferryman") li_ret = 3

string ls_ch //临时单元
string ls_SecondSecTable //存放所有国标二级汉字读音
integer li_num = 0 //返回值
integer i,j

For i = 1 to Len(aString)
ls_ch = Mid(aString,i,1)
If Asc(ls_ch) >= 128 then //是汉字
li_num++
i = i+1
End if
Next

Return li_num

end function

---------------------------------------------------------------

(2)、转到WORD
$PBExportHeader$f_outputtoword_new.srf
global type f_outputtoword_new from function_ O B J E C T
end type

forward prototypes
global function integer f_outputtoword_new (datawindow adw)
end prototypes

global function integer f_outputtoword_new (datawindow adw);
//函数名:f_outputtoword_new
//输入: adw - datawindow,指定的数据窗口
//返回值: Integer
constant integer ppLayoutBlank = 12
OLEObject ole_ O B J E C T
ole_ O B J E C T = CREATE OLEObject

integer li_ret

li_ret = ole_ O B J E C T.ConnectToObject("","word.application")
IF li_ret <> 0 THEN
//如果Word还没有打开,则新建。
li_ret = ole_ O B J E C T.ConnectToNewObject("word.application")
if li_ret <> 0 then
MessageBox('OLE错误','OLE无法连接!错误号:' + string(li_ret))
return 0
end if
ole_ O B J E C T.Visible = True
END IF

long ll_colnum,ll_rownum
constant long wdWord9TableBehavior = 1
constant long wdAutoFitFixed = 0
constant long wdCell = 12
string ls_value
pointer oldpointer

oldpointer = SetPointer(HourGlass!)

string ls_ O B J E C Ts,ls_obj,ls_objs[],ls_objtag[]
long ll_pos,ll_len,ll_num = 0

ls_ O B J E C Ts = trim(adw.Describe('datawindow.Objects'))

do while (pos(ls_ O B J E C Ts,"~t") > 0)
ll_pos = pos(ls_ O B J E C Ts,"~t")
ll_len = ll_pos - 1
ls_obj = left(ls_ O B J E C Ts,ll_len)
if (adw.Describe(ls_obj + '.type') = 'column' or &
adw.Describe(ls_obj + '.type') = 'compute')

and &
(adw.Describe(ls_obj + '.band') = 'detail') and (ls_obj <> "asd") then
ll_num += 1
ls_objs[ll_num] = ls_obj
ls_objtag[ll_num] = adw.Describe(ls_obj + '.tag')
end if
ls_ O B J E C Ts = right(ls_ O B J E C Ts,len(ls_ O B J E C Ts) - ll_pos)
loop

//得到数据窗口数据的列数与行数(行数应该是数据行数 + 1)
ll_colnum = ll_num
ll_rownum = adw.rowcount() + 1

ole_ O B J E C T.Documents.Add()
ole_ O B J E C T.ActiveDocument.Tables.Add(ole_ O B J E C T.Selection.Range, ll_rownum, ll_colnum)

string ls_colname
integer i,j,k

for i = 1 to ll_colnum
//得到标题头的名字
ls_value = ls_objtag[i]
ole_ O B J E C T.Selection.TypeText(ls_value)
for k = 1 to f_cncharnum(ls_value)
ole_ O B J E C T.Selection.TypeBackspace()
next
ole_ O B J E C T.Selection.MoveRight(wdCell)
next

adw.setredraw(false)
ole_ O B J E C T.Selection.MoveLeft(wdCell)
string column_name
for i = 2 to ll_rownum
for j = 1 to ll_colnum
column_name = ls_objs[j]
if adw.Describe(column_name + '.type') = 'column' then
ls_value = adw.Describe("Evaluate('LookupDisplay("+column_name+")',"+string(i - 1)+")")
end if
if adw.Describe(column_name + '.type') = 'compute' then
ls_value = adw.Describe("Evaluate('" + adw.Describe(column_name + '.expression') + "',"+string(i - 1)+")")
end if
ole_ O B J E C T.Selection.MoveRight(wdCell)
ole_ O B J E C T.Selection.TypeText(ls_value)
//for k = 1 to f_cncharnum(ls_value)
//ole_ O B J E C T.Selection.TypeBackspace()
//next
next
next
adw.setredraw(true)

constant long wdFormatDocument = 0

SetPointer(oldpointer)
//保存新建的文档
if messagebox("保存","文档已经成功完成,是否保存?",Question!,YesNo!) = 1 then
string docname, named
integer value

value = GetFileSaveName("选择文件",docname, named, "DOC","Doc Files (*.DOC), *.DOC")

IF value = 1 THEN
ole_ O B J E C T.ActiveDocument.SaveAs(docname, 0,False,"",True,"",False,False,False, False,False)
end if

end if
//断开OLE连接
Ole_Object.DisConnectObject()
Destroy Ole_Object

return 1
end function






38、字段如何自动换行的同时且自动高度?

答:将数据窗口中相应列的auto horz scroll 为不选中,选中autosize height
将detail的autosize height选中。在数据窗口retrieve 后调用下面函数即可

uf_set_text(datawindow adw_content,string
as_columns,boolean,ab_ignoreblank)
/*************************************************************
describe: 在数据窗口adw_content中,在as_columns中包含的列中插入空格
args:
as_columns 要操作的多个列,列间用逗号隔开
***********************

**************************************/
if (not isvalid(adw_content)) or isnull(as_columns) or len(as_columns) <1 or isnull(ab_ignoreblank) then return -1

n_cst_string lnv_string
string ls_column[] , ls_width ,as_source,as_replaced ,ls_temp
int li_upperbound , li_width , li_column , li_fontWidth, li_counter
long ll_rowcount , ll_row , ll_totalstep
int li_yield

lnv_string.of_parsetoarray(as_columns,',',ls_column)
li_upperbound = upperbound(ls_column)
ll_rowcount = adw_content.rowcount()
if li_upperbound <1 or ll_rowcount <1 then return -1

openwithparm(w_waiting,this)
ib_cancel = false
iw_frame.enabled = false
ll_totalstep = ll_rowcount * li_upperbound
w_waiting.uf_register(ll_totalstep)
for li_column = 1 to li_upperbound
ls_width = adw_content.describe(ls_column[li_column]+".width")
li_width = integer(ls_width)
if ls_width='!' or ls_width='?' or li_width=0 then
continue
end if
//ls_temp = adw_content.describe(ls_column[li_column]+".Font.property { = 'width' }")
//messagebox(ls_column[li_column]+".Font.property { = 'width' }",ls_temp)
//return 1
li_fontwidth = 27
li_counter = li_width / li_fontWidth

for ll_row=1 to ll_rowcount
if ib_cancel then
iw_frame.enabled = true
return 0 //pressed cancel button
end if
as_source = adw_content.getitemstring(ll_row,ls_column[li_column])
as_replaced = uf_insertstring(as_source,li_counter,' ',false)
if as_replaced <>as_source then
adw_content.setitem(ll_row,ls_column[li_column],as_replaced)
end if
w_waiting.uf_stepit()
next
next
close(w_waiting)
iw_frame.enabled = true

return 1





39、如何动态外部创建数据窗口?

答:首先制作一个自己想动态得到的数据窗口,然后将该数据窗口导出,看看语法,这样你就了解了这种数据窗口的生成语法了!

---------------------------------------------------------------

dw_1.create()
可以参考帮助 以及 srd文件(数据窗口导出文件)
---------------------------------------------------------------

动态数据窗创建原理及实现

在实际应用中,经常需要根据用户需求来动态创建数据窗,一般方法是这样的。

在一个window中加入一个数据窗控件,如dw_new,但是该数据窗没有data O B J E C T,(空白的)
就可以用以下语法来创建:
dw_new.create(ls_synta

x,ls_error) // 创建语法,错误信息
ls_syntax可以用以下三种方法来形成:

一、动态由sql语法创建:

// 连接到pb的example数据库
string ls_sql,ls_syntax,ls_error
ls_syntax = 'select * from department'
ls_syntax = sqlca.SyntaxFromSQL(ls_sql,'style(type=grid)',ls_error)
if len(ls_error) >0 then
messagebox('Error','SyntaxFromSQL Error:~r'+ls_error)
else
dw_new.create(ls_syntax,ls_error)
if len(ls_error) >0 then
MessageBox("Error", "Create have these errors: ~r" + ls_error)
else
dw_new.settrans O B J E C T(sqlca)
dw_new.retrieve()
end if
end if

二、由另一个数据窗的syntax来创建

string ls_syntax,ls_error
ls_syntax = dw_test.describe('datawindow.syntax')
dw_new.create(ls_syntax,ls_error)
if ls_error <> '' then
messagebox('Create Error',ls_error)
else
dw_new.settrans O B J E C T(sqlca)
dw_new.retrieve()
end if

三、读取psr文件来创建

样例
string ls_syntax,ls_error,ls_ret
ls_ret = char(13)+char(10) //回车键
int li_fileNum
long li_length
li_FileNum = FileOpen("efef.psr",Streammode!, read!, shared!, Replace!)

// 以下是pb5的代码
if li_filenum >0 then
FileSeek(li_FileNum, 158, FromBeginning!)
li_length = fileRead(li_filenum,ls_syntax)
end if
fileclose(li_filenum)
if li_length = 0 then return
ls_syntax = "release 5;"+ls_ret+ls_syntax

//截掉ls_syntax中的数据部分,5.0以"sparse(names="dept_name?) "作为参考位置
//6.0以html(作为参考位置

long pos1,pos2
pos1 = pos(ls_syntax,'sparse(names="',1)
pos2 = pos(ls_syntax,'"',pos1 +16)
ls_syntax = left(ls_syntax,pos1) + mid(ls_syntax,pos1 +1,pos2 - pos1 +1)

dw_New.create(ls_syntax,ls_error)

if ls_error <> '' then
messagebox('Create Error',ls_error)
else
dw_new.settrans O B J E C T(sqlca)
dw_new.retrieve()
end if

//pb6,pb7的代码可以参照pb5自己写,只是文件头和数据窗结束标记不同而已。


---------------------------------------------------------------

global type f_createextenddw from function_ O B J E C T
end type

forward prototypes
global function string f_createextenddw (ref datawindow dw, string cols[])
end prototypes

global function string f_createextenddw (ref datawindow dw, string cols[]);string sql_dw_general, sql_dw_columns_type, sql_dw_headers_conf, sql_dw_columns_conf, ls_errors
int i
long ll_colcount
string ls_colnametype
string ls_colname,ls_coltype
long ll_pos

ll_colcount = upperbound(cols)

//generals
sql_dw_general = "release 8;" &
+ "datawindow(units=0 timer_inte

rval=0 color=16777215 processing=0 print.documentname=" + char(34) + "" + char(34) + " print.orientation = 0 print.margin.left = 110 print.margin.right = 110 print.margin.top = 96 print.margin.bottom = 96 print.paper.source = 0 print.paper.size = 0 print.prompt=no print.buttons=no print.preview.buttons=no )" &
+ "header(height=72 color=" + char(34) + "536870912" + char(34) + " )" &
+ "summary(height=0 color=" + char(34) + "536870912" + char(34) + " )" &
+ "footer(height=0 color=" + char(34) + "536870912" + char(34) + " )" &
+ "detail(height=84 color=" + char(34) + "536870912" + char(34) + " )"


//列及类型
sql_dw_columns_type = "table("
FOR I=1 to ll_colcount
ls_colnametype = trim(cols[i])
ls_colname = right(ls_colnametype,len(ls_colnametype) - 1)
ls_coltype = left(ls_colnametype,1)
choose case upper(ls_coltype)
case 'C'
ls_coltype = 'char(100)'
case 'D'
ls_coltype = 'date'
case 'N'
ls_coltype = 'decimal(6)'
case else
ls_coltype = 'char(100)'
end choose
//ls_coltype = 'char(100)'
//列及类型
sql_dw_columns_type= sql_dw_columns_type + "column=(type=" +ls_coltype+" updatewhereclause=no name=" + ls_colname + " dbname=" + char(34) + ls_colname + char(34) + " ) "

//列标题
sql_dw_headers_conf = sql_dw_headers_conf + "text(band=header alignment=" + char(34) + "2" + char(34) + " text=" + char(34) + ls_colname + char(34) + " border=" + char(34) + "6" + char(34) + " color=" + char(34) + "16711680" + char(34) + " x=" + char(34) + string( ((i - 1) * 588) + 5) + char(34) + " y=" + char(34) + "4" + char(34) + " height=" + char(34) + "64" + char(34) + " width=" + char(34) + "574" + char(34) + " name=" + ls_colname + "_t font.face=" + char(34) + "Arial" + char(34) + " font.height=" + char(34) + "-10" + char(34) + " font.weight=" + char(34) + "400" + char(34) + " font.family=" + char(34) + "2" + char(34) + " font.pitch=" + char(34) + "2" + char(34) + " font.charset=" + char(34) + "0" + char(34) + " background.mode=" + char(34) + "2" + char(34) + " background.color=" + char(34) + "12632256" + char(34) + " )"

//列属性
sql_dw_columns_conf = sql_dw_columns_conf + "column(band=detail id=" + string(i) + " alignment=" + char(34) + "1" + char(34) +

" tabsequence=" + string(i) + "0 border=" + char(34) + "2" + char(34) + " color=" + char(34) + "0" + char(34) + " x=" + char(34) + string( ((i - 1) * 588) + 5) + char(34) + " y=" + char(34) + "4" + char(34) + " height=" + char(34) + "76" + char(34) + " width=" + char(34) + "579" + char(34) + " format=" + char(34) + "[general]" + char(34) + " name=" + ls_colname + " edit.limit=0 edit.case=any edit.autoselect=yes edit.autohscroll=yes font.face=" + char(34) + "Arial" + char(34) + " font.height=" + char(34) + "-10" + char(34) + " font.weight=" + char(34) + "400" + char(34) + " font.family=" + char(34) + "2" + char(34) + " font.pitch=" + char(34) + "2" + char(34) + " font.charset=" + char(34) + "0" + char(34) + " background.mode=" + char(34) + "1" + char(34) + " background.color=" + char(34) + "536870912" + char(34) + " )"

NEXT

sql_dw_columns_type= sql_dw_columns_type + " )"

sql_dw_columns_conf = sql_dw_columns_conf + "htmltable(border=" + char(34) + "1" + char(34) + " cellpadding=" + char(34) + "0" + char(34) + " cellspacing=" + char(34) + "0" + char(34) + " generatecss=" + char(34) + "no" + char(34) + " nowrap=" + char(34) + "yes" + char(34) + ")"

//MESSAGEBOX('',sql_dw_general + sql_dw_columns_type + sql_dw_headers_conf + sql_dw_columns_conf)
dw.Create(sql_dw_general + sql_dw_columns_type + sql_dw_headers_conf + sql_dw_columns_conf , ls_errors)

return(ls_errors)
end function





40、如何让datawindow的heade带区r的内容只打印一次?

答:a、制作两个数据窗口,第一个有表头,第二个没有。
b、用第一个有表头的数据读取数据库中的数据
c、打印有表头的数据窗口中的第一页,记住结束行号
d、将从结束行号开始的所有数据复制到第二个数据窗口中
e、打印第二个数据窗口

41、交叉报表在retrieve后,其datawindow的宽度怎么获得啊?

答://====================================================================
// [PUBLIC] Function wf_settitle_length 在 w_search_report inherited from window
//--------------------------------------------------------------------
// 说明:设置表头长度
//--------------------------------------------------------------------
// 参数1:[reference] datawindow adw_1
// 说明:报表DW
//--------------------------------------------------------------------
// 返回: (INTEGER) 成功返回1,不成功返回0
//--------------------------------------------------------------------
// 作者: cwl 日期: 2001.12.15
//====================================================================
Long

Row
String List
string token[]
String tag_1
Integer StartPos = 1, EndPos, Top, i = 1 , index = 0
//取出DW中所有的对象存入token[]中
list = adw_1.Describe("datawindow. O B J E C Ts")
EndPos = pos(list, '~t', StartPos)
Do while ( EndPos > 0 )
token[i] = Mid(list, StartPos, EndPos - StartPos)
i ++
StartPos = EndPos + 1
EndPos = pos(list, '~t', StartPos)
LOOP
token[i] = Mid(list, StartPos)
Top = UpperBound(token[])

//找出最后一列
string ls_lastcol
int li_lastpos=0,li_thispos
For i = 1 to Top
CHOOSE CASE UPPER(adw_1.Describe(token[i] + '.type'))
CASE 'COLUMN', 'COMPUTE'
li_thispos = integer(adw_1.Describe(token[i] + '.X'))
if li_thispos>=li_lastpos then //这是目前最后一列
li_lastpos=li_thispos
ls_lastcol=token[i]
end if
end choose
NEXT
//设置表头长度
string ls_change
ls_change="800~tlong(describe('"+ls_lastcol+".x')) + long(describe('"+ls_lastcol +".width')) + 10"
//messagebox('',ls_change)
adw_1.modify('title.width="'+ls_change+'"')

return 1


42、如何在数据窗中得到自动高的列的高度?

答:desceibe("evaluate('RowHeight()',3)") //获得第三行的row的高度


42、如何使dw的列不可移动,不可调整列宽?

答:在datawindow的cilcked事件写

if row=0 then
return 1
end if


43.光标跳转到数据窗口的某一行某一列

dw_1.scrolltorow(ll_row)
dw_1.setcolumn(ll_column)



44 如何使光标指向每页第一行?


long ll_firstrowonpage=long(dw_1.describe("datawindow.firstrowonpage"))

dw_1.scrolltorow(ll_firstrowonpage)

dw_1.setrow(ll_firstrowonpage)

45. Grid的窗口如何使第一列固定不动?



①选上data OBJECT的HSplitScroll属性
②在constructor事件中:
dw_1.Object.DataWindow.HorizontalScrollSplit=integer(dw_1.describe("#1.width")) //第一列的宽度
③在scrollhorizontal事件中:
int i

if pane = 1 then

i = integer(this.OBJECT.datawindow.horizontalscrollposition2)

if i < 1 or isnull(i) then return

if scrollpos > 0 then

this.OBJECT.datawindow.horizontalScrollPosition = 0

end if

else

i = integer(this.Object.DataWindow.HorizontalScrollSplit)

if i < 1 or isnull(i) then return

if i > scrollpos then

this.OBJECT.d

atawindow.horizontalScrollPosition2 = i

end if

end if





46. 怎样取子数据窗口的总列数

ll_column_count=integer(dwc.describe("datawindow.column.count")) //dwc为子窗口

47.在数据窗口过滤以后,计算列值如何才能一起改变?

dw_1.setfilter(filter_condition)

dw_1.filter()

dw_1.groupcalc()

48.怎么改变某一列的背景颜色?

dw_1.Modify("sno.background.mode=2" )

dw_1.Modify ( "sno.background.Color='255'" )
49.在数据窗口中如何delete选中的多行?

Long ll_rows , ll_row
ll_rows=DW_1.RowCount()
for ll_row = ll_rows to 1 step -1
if dw_1.isSelected(ll_row) then
dw_1.DeleteRow(ll_row)
end if
next

50.如何改变列的字体颜色,提醒用户此列已做修改
在列的Color属性中,输入如下表达式
IF (column_name < >column_name.Original, RGB(255, 0, 0), RGB(0, 0, 0))


51.数据窗口中限定某列不可编辑

用DataWindow的clicked事件中的方法也可以实现列的保护。若
某列不可更改,则可置r otect=0。即:
dw_1.modify("columnname.protect=0")
或dw_1.modify("#"+string(number)+".protect=0")
若要将该列改为可更改,则置protect=1,即:
dw_1.modify(:columnname.protect=1")
或dw_1.modify("#"+string(number)+".protect=1")
此方法不影响Tab键的移动,用户可以随意拉动列,还可在应用过
程中自己决定哪一列可编辑,哪一列不可编辑。

52.怎样去掉上图中数据窗口中的黑影?

this.Modify ("DataWindow.selected.mouse=no")
this.Modify ("DataWindow.Grid.ColumnMove = false")

53 实现逐行增加求和

使用计算列:CumulativeSum(field for all),即可达到逐渐递增求和的功能


54 快速删除多行

方法是把要删除的行从主缓冲区中移到删除缓冲区中。例如,删除缓冲区中所有的行:
dw_1.RowsMove(dw_1, 1, dw_1.RowCount, Primary!, dw_1, 1, Delete!)

58、在分组的header上加序号

答:建立计算域,expression: cumulativeSum( If (jlxm = jlxm[-1],0,1) for all)

59、为什么varchar字段类型的列只能保存255个字符?

答:设置事务处理对象的dbparm属性即可

示例:

.........

SQLCA.dbParm = "DBTextLimit = '9999'"

.........

60、点击grid类型数据窗口的header,自动排序。(图片自己做)

/*
*args: i_str_oldcol
*note:实例变量,纪录上次点击的列
*/
string i_str_oldcol

string str_ O B J E C Tname, str_curcol, str_addpic
integer int_pic_x

str_ O B J E C Tname =string (https://www.360docs.net/doc/6213276731.html,) //对象名称
if row = 0 and this.describe(str_ O B J E C Tname+".band") = "header" and this.describe(str_ O B J E C Tname+".text") <> "!" then //是否点击列对象
str_curcol = left(str_ O B J E C Tname,len(str_ O B J E C Tname) - 2) //当前列对象名称
if str_curcol <> i_str_oldcol then //点击的是不同列对象

this.modify("destroy p_sort") //不管有没有位图对象都删除
i_str_oldcol = str_curcol //保存上次点击的列对象
//画图
int_pic_x = integer(this.describe(str_ O B J E C Tname+".x")) + (integer(this.describe(str_ O B J E C Tname+".width")) - 70)
str_addpic = 'create bitmap(band = foreground filename= "..\pic\up.bmp" x= "'+string(int_pic_x)+'" y= "24" height= "48" width= "48" border= "0" name= p_sort visible= "1")'
this.modify(str_addpic) //动态画个图
this.setsort(str_curcol + " A") //头一次点击当然是升序了
this.sort()
else //当前列已经点过了
if this.describe("p_sort.filename") = "..\pic\up.bmp" then //上次是升序
this.modify("p_sort.filename = '..\pic\down.bmp'")
this.setsort(str_curcol + " D") //这次是降序
else
this.modify("p_sort.filename = '..\pic\up.bmp'")
this.setsort(str_curcol + " A")
end if
this.sort()
end if
end if







1.pb9应用xp风格
将PB9升级到7119后,编译时有一个 New Visual Style Controls 选项,选中后,编译出来的文件在XP下就可以应用XP风格了
2.Yield()函数的作用
Yield()是一个不常用到的PowerBuilder函数。可是,在一个大的循环过程中,如果用户想在执行到一半时通过单击按钮或菜单来退出的话,就一定要用到Yield()函数了,否则程序只会在执行完成整个循环后才会响应按钮或菜单的Click事件。将Yield()函数放在循环体的中间。那么在循环执行的过程中发现有新的事件消息在消息队列中就回立即去响应。

Yield()
功能将控制权转移给其它图形对象,包括非PowerBuilder对象。该函数检测消息队列,如果有消息,就把消息取出。利用该函数可以在执行耗时较长的操作时把控制权转让给其它应用。
语法Yield()
返回值Boolean。如果在消息队列中提取到了消息,那么函数返回TRUE,否则返回FALSE。用法正常情况下,PowerBuilder应用程序在执行一段代码(比如函数或事件处理程序)的过程中不响应用户的操作。对耗时短暂的代码段来说,这种处理方式没有什么不妥的地方,但是,如果某个代码段的执行耗时较长,应用程序又希望为用户提供更多的控制权,那么需要在这段代码中插入Yield()函数,让用户能够进行其它操作,特别在循环执行的代码中更应该如此。应用程序执行Yield()函数后,如果发现消息队列中存在消息,它将允许对象处理这些消息,处理之后,继续Yield()函数后面代码的执行。因此,代码中插入Yield()函数将降低应用程序的运行效率。
3.sqlca.SQLCode 与update()
在利用Embedded SQL 的时候,每运行一次SQL指令就应该检查一次交易对象中的属性SQLCode,而不是等到

有的SQL指令运行完毕后再去运行检查交易对象中的SQLCode属性.当我们使用数据窗口所提供的函数时,
要记住不要检查SQLCode来判断是否运行成功.而是要依照每一个函数运行后所返回的值来判断是否运行
成功.
update tab_test set col1 = 'test'
if sqlca.sqlCode = -1 then
rollback using sqlca;
if sqlca.sqlCode = -1 then
messageBox('错误','连接失败!')
end if
messageBox('错误','连接失败!')
else
commit using sqlca;
end if
//确保数据保存的成功
if dw_1.update() = -1 then
RollBack Using SQLCA;
MessageBox("警告!","数据保存失败!")
else
Commit Using SQLCA;
End if

4.读取网页内容:
sle_1.text=ole_1.object.Document.body.outertext
ole_1.object.Document.body.scroll="no"
mle_1.text=ole_1.object.document.body.outerhtml

5. tab_1.createondemand 在需要时创建:
tab_1.createondemand:在需要时创建。提高在open事件时的效率,tab_1的某一tabpage里的内容在open时不创建,仅当选择该页时或selecttab才创建,不过,在未创建时,不能对其中的控件及属性引用。


6.如何在程序中对BLOB数据库进行写入
和后台数据库有关:以SQLANYWAY为例:
一般用 UPDATEBLOB 和 SELECTBLOB 两个SQL语句来实现。
建一个表TABLE1,一个字段是ID,另一个是BLOB,
SELECTBLOB BLOB FROM TABLE1 WHERE ID='xx';
UPDATEBLOB SET BLOB = :BLB_X FROM TABLE1 WHERE ID='yy';
删除时删除ID为'mm'的记录即可,新增是先插入一条ID为'mm'的记录,然后 用UPDATEBLOB将数据写入
表内。 其他的数据库可参照手册进行,其命令与上述差别不大!

7.API、系统消息及其它dll调用
1.控件可拖动:
send(handle(this),274,61458,0)
2.如何屏蔽鼠标滚轮触发
在控件的other事件写
if message.number = 522 then return 1

3.隐藏任务栏的方法,
在OnCreate事件里利用Window API函数SetWindowLong:SetWindowLong(Application.Handle,GWL_EXSTYLE,WS_EX_TOOLWINDOW);
PB使用时首先声明函数FUNCTION long SetWindowLong(ulong hWnd, integer nIndex, ulong dwNewLong) library "user32.dll" ALIAS FOR "SetWindowLongA",
然后调用:SetWindowLong(Handle(this),-20,128);

4.在PB中调用屏幕保护的方法:
send(handle(This),274,61760,0)

5.得到一个应用程序如Outlook的路径
RegistryGet("HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionApp PathsMSIMN.EXE", &
"Path",ls_outlook_path)
//Outlook的路径将保存在string型变量ls_outlook_path中。

6.得到程序运行时的路径
//在global external functions声明:
Function uLong GetModuleFileNameA(long hinstModule, Ref String lpszPath, uLong cchPath) Library ″kernel32.dll″
//程序路径保存在变量ls_AppPath中
string ls_AppPath
int li_ret
ls_AppPath = Space(128)
li_ret = GetModuleFileNameA(Handle(GetApplication()),ls_apppath,128)
//要编译成可执行文件.exe才

可用,否则得到的是Powerbuilder的pb60.exe或PB050.exe的路径。

7.屏蔽窗口的ALT+F4键
//方法一:
1.在窗口的systemkey事件中增加以下代码:
IF KeyDown(KeyF4!) THEN
Message.Processed = TRUE
END IF
2.在窗口的closequery事件中增加如下代码:
Long ll_ret
IF KeyDown(keyF4!) THEN
ll_ret = 1
END IF
return ll_ret
//方法二:
建一实例变量,在你的关闭程序上赋一个True然后在closequery中判断该值, 如为False则Return 1

8.当程序中用到了动态加入的对象,如BMP资源文件、数据窗口对象,PB编译时是扫描不到的,解决方法:
1.将此对象写入到资源文件中:
用记事本创建资源文件dw_object.pbr,写入:c:myprogram.pbl(dw_sj)
编译时将此文件选入Resource File Name处。
2.将应用编译成PBD、DLL文件。
9.如何在PB中实现延时:
subroutine Sleep(long dwMilliseconds) library "kernel32.dll"
延时1秒则调用: Sleep(1000) //单位是毫秒。

10.调用API函数步骤:
1、在适当的位置声明函数,如窗口内,Application内,UserObject内,
定义在Local External Function或Global External Function中,如播放声音的:
Function boolean sndPlaySoundA(string SoundName, uint Flags) Library "WINMM.DLL"
Function uint waveOutGetNumDevs() Library "WINMM.DLL"
也可以创建一个UserObject,集中声明常用的API及函数本地化,如定义用户对象 u_external_function:
Declare Local External Function(定义外部函数):
Function boolean sndPlaySoundA(string SoundName, uint Flags) Library "WINMM.DLL"
Function uint waveOutGetNumDevs() Library "WINMM.DLL"
Declare User Object Function(定义用户对象函数):
uf_play_sound(string as_wave_name, integer ai_option)
函数内容如下:
//参数:as_wave_name :wav文件名 ai_option :同步或异步(1/0)
uint lui_numdevs
lui_numdevs = WaveOutGetNumDevs()
If lui_numdevs > 0 Then
sndPlaySoundA(as_wave_name,ai_option)
return 1
Else
return -1
End If
2、调用时在程序中定义一个实体并调用其函数:
u_external_function iu_external_function
iu_external_function = create u_external_function
iu_external_function.uf_play_sound('c:windowsmediading.wav',1)
试试看,如果有声卡,就会听到"叮”的一声。其它API函数也是如此处理。

11.显示一个与Windows操作系统风格一致的About对话框。
首先声明如下外部函数:
function int ShellAboutA(ulong al_hWnd, string as_szApp, string as_szOtherStuff, ulong hIcon) library "shell32"
ShellAboutA(handle(parent),"关于... ","欢迎",0)







12.send用法:Send(handle,message#,lowword,long)
数据窗口中按enter键实现tab功能(在数据窗口的Enter事件中)
自定义事件ID:pbm_dwnprocessenter里写如下代码:
Send(Handle(This),256,9,Long(0,0))

说明:This代表DW;Handle代表DW的句柄;256代表TAB键;9代表不加入shift键,7

代表加入;Long(0,0)代表预留空位.

send(handle(this),256,9,long(0,0))
return 1
//This statement scrolls the window w_emp up one page:
Send(Handle(w_emp), 277, 2, 0)
//Both of the following statements click the CommandButton cb_OK:
Send(Handle(Parent), 273, 0, Handle(cb_OK))
cb_OK.TriggerEvent(Clicked!)
//minimizes the DataWindow:
Send(Handle(dw_1), 274, 61472, 0)
//maximizes the DataWindow:
Send(Handle(dw_1), 274, 61488, 0)
//returns the DataWindow to its normal, defined size:
Send(Handle(dw_1), 274, 61728, 0)

13.如何使PB窗口总在最上层(Always On Top)
通过SetWindowPos函数把窗口的显示层次修改为HWND—TOPMOST,就可使指定窗口永远不会被其它窗口覆
盖,该函数声明为:
Function Long SetWindowPos(Long hwnd,Long ord,Long x,Long y,Long dx,Long dy,Long uflag) Library ″user32″
参数1为要顶层显示的窗口句柄,参数2指定显示的层次,参数7为附加选项,其余参数指定窗口位置和
大小,均可忽略。在窗口的Open或Activate事件中加入如下函数调用:
SetWindowPos(Handle(This),-1,0,0,0,0,3)
参数2取-1表示在最顶层显示窗口,取1表示在最底层显示;最后一个参数若取1,表示窗口大小保持不
变,取2表示保持位置不变,因此,取3(=1+2)表示大小和位置均保持不变,取0表示将窗口的大小和
位置改变为指定值。

14.在PB中如何获得光盘盘符
通过GetDriveType函数可以获取驱动器(如:软驱、硬盘、光驱、网络映射驱动器等)的信息,该函数
声明为:
Function Uint GetDriveTypeA(String drive) Library ″kernel32.dll″
参数为一个盘符(如"C:"),返回值:1表示未知,2表示软驱,3表示本地硬盘,4表示网络驱动器,
5表示光驱。因此如下代码可以获得光盘的盘符:
For i=Asc(′D′) to Asc(′Z′)
//列举所有可能的CDROM驱动器
If GetDriveTypeA(Char(i)+″:″)=5 Then
//若找到CDROM
MessageBox(″CDROM″,Char(i)+″:″)
//显示光盘盘符
Exit //退出列举
End If
Next

15.在PB中如何获取目录信息
⑴获取当前目录。通过GetCurrentDirectory函数可以获取当前目录,该函数声明为:
Function Ulong GetCurrentDirectoryA(Ulong buflen, ref String dir) Library ″kernel32.dll″
参数2为接收当前目录的字符缓冲区,前面必须加ref表示地址引用;参数1用来指定字符缓冲区的长度。
调用过程为:
String curdir
curdir=Space(256)
//为字符缓冲区开辟内存空间
GetCurrentDirectoryA(256,curdir)
MessageBox(″Current Directory″,curdir)
⑵获取Windows及系统目录。要用到GetWindowsDirectory和GetSystemDirectory两个函数,须作如下声明:
Function Uint GetWindowsDirectoryA(ref String dir,Uint buflen) Library ″kernel32.dll″
Function Uint GetSystemDirectoryA(ref String dir,Uint buflen) Library ″kernel3

2.dll″

16.在PB中如何注销当前用户、关闭计算机、重启计算机
通过ExitWindowsEx函数可实现这三个功能,首先作如下声明:
Function Long ExitWindowsEx(Long uflag,Long nouse) Library ″user32.dll″
参数2保留不用,可取0;参数1取0可以注销当前用户,取1可以关闭计算机,取2可以重启计算机,其值
再加4表示强制结束"未响应"的进程。

17.控制由Run运行的程序(简称Run程序)
在PB程序设计中,可以用Run()来运行一些程序。比如用户按了F1,就运行一个chm文件。但Run程序无法
与PB主程序协调工作,若用户按了多次F1,就会启动Run程序的多个实例,主程序退出时,Run程序依然
运行。可以用如下函数来使它们协调工作:
Function Ulong FindWindowA(Ulong classname, String windowname) Library ″user32.dll″
Function Long SetParent(Long childwin,Long parentwin) Library ″user32.dll″
⑴使Run程序只运行一个实例
handle=FindWindowA(nul,wtitle)
//查找Run程序是否已经运行,wtitle为Run程序的标题
IF handle〉0 Then Return
//若已经在运行就返回
Run(″C:Program FilesJointJoint.chm″)
//否则运行Run程序
⑵PB主程序退出时,Run程序也关闭
handle=FindWindowA(nul,wtitle)
SetParent(handle,Handle(w—main))
//使Run程序窗口成为PB主程序的子窗口

18.映射网络驱动器
若要在程序中把远程主机的资源映射到本地驱动器,可以用如下函数:
Function long WNetAddConnectionA(String path,string pwd,String drv) Library ″mpr.dll″
19.在PB中如何打开一个文件(如.txt,.doc),就像在资源管理器中双击打开文件一样?
答:可以通过API函数来实现。
在应用程序的Global External Functions中定义:
Function long ShellExecuteA(ulong hwnd, string lpOperation, string lpFile, & string
lpParameters, string lpDirectory, long nShowCmd) library "shell32.dll”
调用如下:
String ls_null
SetNull(ls_null)
ShellExecuteA(Handle(Parent), ls_null, "c:dochello.txt”, ls_null, ls_null, 1)
20.PB中实现淡入淡出效果
声明API:
function Boolean AnimateWindow( ulong hwnd, long dwTime, long dwFlags) library 'user32.dll'
窗口 open事件:
////---------------------------------------------------------------
long ll_handle
ll_handle = Handle ( this )
AnimateWindow ( ll_handle , 1000, 524288+16)//淡进
//////-------------------------------- ------------------------
窗口close事件
AnimateWindow ( Handle ( This ) , 300, 524288+ 65536 + 16)//淡隐






21.SendMessage API函数在PowerBuilder中应用
一、引言
在Powerbulider巧妙地调用API函数SendMessage,可以完成Pb中的一些用常规的方法而很难实
现的功能,特将对该api函数在Powerbuilder中的使用,例举几

个方面的运用,以期起到抛砖引玉的效果(以下代码完全可以使用PowerBuilder中的Send函数替代SendMessage 这个Api函数,因起稿比较匆忙,代码未经测试)
二、函数说明
SendMessage函数说明:
说明
调用一个窗口的窗口函数,将一条消息发给那个窗口。除非消息处理完毕,否则该函数不会返回。SendMessageBynum, SendMessageByString是该函数的"类型安全"声明形式
返回值
Long,由具体的消息决定
参数表
参数 类型及说明
hwnd Long,要接收消息的那个窗口的句柄
wMsg Long,消息的标识符
wParam Long,具体取决于消息
lParam Any,具体取决于消息
Powerbuilder中已使用函数Send函数对其进行了封装
函数原形:Send ( handle, message#, lowword, long )
Send函数说明:
说明
调用一个窗口的窗口函数,将一条消息发给那个窗口。除非消息处理完毕,否则该函数不会返回。
返回值
Long,由具体的消息决定
参数表
参数 类型及说明
handle Long,要接收消息的那个窗口的句柄
message# Long,消息的标识符
lowword Long,具体取决于消息
long long,具体取决于消息
3、 应用举例
定义外部函数引用声明:
funcation long SendMessage (long hwnd As Long,long wMsg , long wParam,long lParam) Library "user32.dll" Alias for "SendMessageA"
funcation long ReleaseCapture() Library "user32.dll"
定义实例变量:
Constant long LB_ITEMFROMPOINT = 425
Constant long HTCAPTION = 2
Constant long WM_NCLBUTTONDOWN = 161
Constant long EM_GETLINE = 404
Constant long EM_GETLINECOUNT = 399
Constant long EM_GETLINECOUNT = 186
Constant long EM_GETLINE = 196
Constant long TVM_SETITEMHEIGHT = 4379
Constant long EM_LINESCROLL = 182
Constant long EM_LIMITTEXT=197
1、列表框中鼠标移动时检测位置项
Powerscript:
在列表框的自定义事件ue_mousemove(pbm_mousemove)中写入如下代码:
pos = unitstopixels(parent.pointerx(),XUnitsToPixels!)+ unitstopixels(parent.pointery(),yUnitsToPixels!) * 65536
idx = SendMessage(handle(this), LB_ITEMFROMPOINT, 0, pos) If idx < 65536 Then sle_1.Text = lb_1.text(idx)
2、在列表框中查找匹配的项目
Powerscript:
窗口的open事件:
lb_1.AddItem ("软件")
lb_1.AddItem("电脑游戏")
lb_1.AddItem("电视机")
lb_1.AddItem("电视台")
lb_1.AddItem("电脑")
lb_1.AddItem("电脑游戏软件")
singlelineedit控件的modified事件:
long li_index
li_index= SendMessage(handle(this), EM_GETLINECOUNT, -1, sle_1.text)
lb_1.selectitem(li_index)
3、为ListBox添加水平滚动条
Powerscript:
窗口的open事件:
lb_1.AddItem("软件")
lb_1.AddItem("电脑游戏")
lb_1.AddItem("电视机")
lb_1.AddItem("电视台")
lb_1.AddItem("电脑")
lb_1.AddItem("电脑游戏软件")
SendMessage (handle(this), EM_GETLINE, 250, 0)
4、实现拖动无标题栏窗体
Powerscr

相关主题
相关文档
最新文档