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_dlcode [-1] and <p>[NextPage][/NextPage]</p>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='')
<p>[NextPage][/NextPage]</p>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
PB問答:
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中的圖形到剪切板?
<p>[NextPage][/NextPage]</p>答: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的第一個列<p>[NextPage][/NextPage]</p>,在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版本<p>[NextPage][/NextPage]</p>的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.GetRo<p>[NextPage][/NextPage]</p>w()
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 = <p>[NextPage][/NextPage]</p>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' th<p>[NextPage][/NextPage]</p>en
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]+".wi<p>[NextPage][/NextPage]</p>dth")
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_syntax,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("E<p>[NextPage][/NextPage]</p>rror",
"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_interval=0 color=16777215 processing=0 print.documentname=" +
char(34) + "" + char(34) + " p<p>[NextPage][/NextPage]</p>rint.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<p>[NextPage][/NextPage]</p>(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、打印有表頭的數據窗口中的第一頁,記<p>[NextPage][/NextPage]</p>住結束行號
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 <p>[NextPage][/NextPage]</p> 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.datawindow.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")
<p>[NextPage][/NextPage]</p>或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 (dwo.name) //對象名稱
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
=<p>[NextPage][/NextPage]</p>===================玉兒整理=====================
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數據庫進行寫入
和后台數據庫<p>[NextPage][/NextPage]</p>有關:以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內,U<p>[NextPage][/NextPage]</p>serObject內,
定義在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) Libr<p>[NextPage][/NextPage]</p>ary ″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 ″kernel32.dll″
16.在PB中如何注銷當前用戶、關閉計算機、重啟計算機
通過ExitWindow***函數可實現這三個功能,首先作如下聲明:
Function Long ExitWindow***(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) Libr<p>[NextPage][/NextPage]</p>ary
″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函數說明:
說明
調用一<p>[NextPage][/NextPage]</p>個窗口的窗口函數,將一條消息發給那個窗口。除非消息處理完畢,否則該函數不會返回。
返回值
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、實現拖動無標題欄窗體
Powerscript:
在窗口的自定義事件ue_lbuttondown(pbm_lbuttondown)
long ReturnVal
x = ReleaseCapture()
ReturnVal = SendMessage(hwnd,
WM_NCLBUTTONDOWN, HTCAPTION, 0)
5、獲取多行文本框行數
Powerscript:
Commandbutton的clicked事件
Messagebox("", SendMessage(handle(mle_1),
EM_GETLINECOUNT, 0, 0))
6、設置樹型列表控件標題行高度
Powerscript:
tv_1的constructor事件:
SendMessage(handle(tv_1), TVM_SETITEMHEIGHT, 60, 0)
7、突破Powerbuilder中的多行文本框32k的限制
Powerscript:
SendMessage(handle(mle_1), EM_LIMITTEXT, 65534, 0)
8、用程序代碼控<p>[NextPage][/NextPage]</p>制文本框的滾行與滾列
Powerscript:
SendMessage(handle(sle_1), EM_LINESCROLL, 0, 1)//下卷一行
SendMessage(handle(sle_1), EM_LINESCROLL, 0, -1)//上卷一行
SendMessage(handle(sle_1), EM_LINESCROLL, 1, 0)//右卷一列
SendMessage(handle(sle_1), EM_LINESCROLL, -1, 0)//左卷一列
三、結束語
在編寫Powerbuilder應用時,應該充分調用相關的api函數來擴充pb的一些不足。
來自CSDN網站a78782295博客
轉載請保留出處:http://www.01yun.com/web/20130625/519448.html本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。