VB与Windows API 间的呼叫技巧[3]

[入库:2005年8月18日] [更新:2007年3月24日]

本文简介:选择自 firetoucher 的 blog

        dim  bstr5   as  string           bstr
        dim  hlstr5  as  string(255)      hlstr

    vb5中win32 api的呼叫请多多使用bstr,因为使用hlstr的结果是,vb还得做hlstr
-> bstr的转换来呼叫win api若有传回string而後再做bstr->hlstr的工作。然而使用
bstr来工作时,若处理有传回值的string参数,则还要有额外的动作:

    1.先给定字串的初值,且字串的长度要够放传回值。
    2.传回後,去除传回值中多余的字元。

    或
例如:
-----------------------------------------------------------------------------
int getwindowtext(
    hwnd        hwnd,           // handle of window or control with text
    lptstr      lpstring,       // address of buffer for text
    int         nmaxcount       // maximum number of characters to copy
   );
   该 api 取得window  title bar的文字,而传回值是放入lpstring的character个数。
vb的宣告如下:

decl are function getwindowtext lib "user32" alias "getwindowtexta" _
       (byval hwnd as long,  _
        byval lpstring as string,  _
        byval cch as long)  as long
范例一
*****************************************************************************
dim charcnt as long
dim lpstring as string
dim tmpstr as string
dim nullpos as long

form1.caption = "这是一个test"
lpstring = string(255, 0)  ’设定初值
charcnt = getwindowtext(me.hwnd, lpstring, 256)  ’charcnt = 12
tmpstr = left(lpstring, charcnt) ’如此做会有一些问题
debug.print len(tmpstr)   ’得12
label1.caption = left(lpstring, charcnt)
debug.print len(label1.caption) ’得8
*****************************************************************************

    以范例一的例子来看,设定lpstring= string(255,0)的目的,是设定255个字元的
空间给 lpstring(加上最後的null一共256),charcnt的值是12,明眼者可看到len("这
是一个test") 会是8,但charcnt是12, 所以直接使用left()函数来取得子字串会有问
题,这是unicode与ansi string间的关系,所以了,当您看到有些书的范例用这种方法
取子字串,是不太完善的,所以改用范例二的方式,比较正确。

范例二
*****************************************************************************
form1.caption = "这是一个test"
lpstring = string(255, 0)  ’设定初值
charcnt = getwindowtext(me.hwnd, lpstring, 256)  ’charcnt = 12
nullpos = instr(1, lpstring, chr(0), vbbinarycompare)
tmpstr = left(lpstring, nullpos - 1)
lable1.caption = tmpstr
*****************************************************************************
四、 null 值的传递

    我们再回到求productid的问题,我们已知使用regopenkeyex()来取得subkey的han
dle值,紧接著便是用regqueryvalueex()来取值。

-----------------------------------------------------------------------------
long regqueryvalueex(
    hkey     hkey,              // handle of key to query
    lptstr   lpszvaluename,     // address of name of value to query
    lpdword  lpdwreserved,      // reserved
    lpdword  lpdwtype,          // address of buffer for value type
    lpbyte   lpbdata,           // address of data buffer
    lpdword  lpcbdata           // address of data buffer size
   );
vb的宣告(由api检视员中copy下来者)

本文关键:Visual Basic
 

本站最佳浏览方式为 分辨率 1024x768 IE 6.0(或更高版本的 IE浏览器)

go top