HAWQ技术解析(十) —— 过程语言

        HAWQ支持用户自定义函数(user-defined functions,UDF),还支持给HAWQ内部的函数起别名。编写UDF的语言可以是SQL、C、Java、Perl、Python、R和pgSQL。其中除SQL和C是HAWQ的内建语言,其它语言通常被称为过程语言(PLs),支持过程语言编程是对HAWQ核心的功能性扩展。HAWQ我所使用过的SQL-on-Hadoop解决方案中唯一支持过程化编程的,Hive、SparkSQL、Impala都没有此功能。对于习惯了编写存储过程的DBA来说,这无疑大大提高了HAWQ的易用性,冲这点也得给HAWQ点个赞。这里主要研究HAWQ内建的SQL语言函数和PL/pgSQL函数编程。为了便于说明,执行下面的SQL语句创建一个名为channel的示例表,并生成一些数据。后面定义的函数大都以操作channel表为例。
create table channel (
    id int not null,
    cname varchar(200) not null,
    parent_id int not null);

insert  into channel values (13,'首页',-1);
insert  into channel values (14,'tv580',-1);
insert  into channel values (15,'生活580',-1);
insert  into channel values (16,'左上幻灯片',13);
insert  into channel values (17,'帮忙',14);
insert  into channel values (18,'栏目简介',17);

select * from channel;

analyze channel;
一、HAWQ内建SQL语言
        缺省时,在HAWQ的所有数据库中都可以使用SQL和C语言编写用户自定义函数。SQL函数中可执行任意条数的SQL语句。在SQL函数体中,每条SQL语句必须以分号(;)分隔。SQL函数可以返回void或返回return语句指定类型的数据。由于HAWQ只有函数而没有存储过程的概念,returns void可用来模拟没有返回值的存储过程。所有非returns void函数的最后一句SQL必须是返回指定类型的select语句,函数返回最后一条查询语句的结果,可以是单行或多行结果集。下面是SQL函数的几个例子。
create function fn_count_channel() returns bigint as $$
    select count(*) from channel;
$$ language sql;
        该函数没有参数,并返回channel表的记录数,函数的调用结果如图1所示。
图1
        修改上面定义的函数:
create or replace function fn_count_channel() returns bigint as $$
    select count(*) from channel;
    select count(*) from channel where parent_id=-1;
$$ language sql;
        该函数体内执行了两条查询语句。在函数参数和返回值的定义没有变化时,可以使用create or replace重新定义函数体,该语法与Oracle类似。如果函数参数或返回值的定义发生变化,必须先删除再重建函数。函数返回最后一条查询语句的结果,即parent_id=-1的记录数,调用结果如图2所示。
图2
        再次修改fn_count_channel()函数:
create or replace function fn_count_channel() returns bigint as $$
    select count(*) from channel;
    create table t1 (a int);
    drop table t1;
    select count(*) from channel where parent_id=-1;
$$ language sql;
        函数体中也能执行DDL语句,调用结果如图2相同。
        改变fn_count_channel()函数的返回值类型,必须先删除再重建,不能使用create or replace语法。
db1=# create or replace function fn_count_channel() returns void as $$
db1$# $$ language sql;
ERROR:  cannot change return type of existing function
HINT:  Use DROP FUNCTION first.
db1=# select fn_count_channel();
 fn_count_channel 
------------------
                3
(1 row)

db1=# drop function fn_count_channel();
DROP FUNCTION
db1=# create or replace function fn_count_channel() returns void as $$
db1$# $$ language sql;
CREATE FUNCTION
db1=# select fn_count_channel();
 fn_count_channel 
------------------
 
(1 row)
        该函数没有返回值,而且函数体内没有任何SQL语句。

二、PL/pgSQL函数
        SQL是关系数据库使用的查询语言,其最大的特点是简单易学,但主要问题是每条SQL语句必须由数据库服务器独立执行,而且缺少必要的变量定义、流程控制等编程手段。过程语言解决的就是这个问题。顾名思义,PL/pgSQL以PostgreSQL作为编程语言。它能实现以下功能:
  • 建立plpgsql函数。
  • 为SQL语言增加控制结构。
  • 执行复杂计算。
  • 继承所有PostgreSQL的数据类型(包括用户自定义类型)、函数和操作符。
        每条SQL语句由数据库服务器独立执行模式下,客户端应用向数据库服务器发送一个查询请求后,必须等待处理完毕,接收处理结果,做相应的计算,然后再向服务器发送后面的查询。通常客户端与数据库服务器不在同一物理主机上,这种频繁地进程间通信增加了网络开销。使用PL/pgSQL函数,可以将一系列查询和计算作为一组保存在数据库服务器中。它结合了过程语言的强大功能与SQL语言的易用性,并且显著降低了客户端/服务器的通行开销。正因如此,UDF的性能比不使用存储函数的情况会有很大提高。
  • 消除了客户端与服务器之间的额外往复,只需要一次调用并接收结果即可。
  • 客户端不需要中间处理结果,从而避免了它和服务器之间的数据传输或转换。
  • 避免多次查询解析。
        PL/pgSQL自动在所有HAWQ数据库中安装。
        PL/pgSQL函数参数接收任何HAWQ服务器所支持的标量数据类型或数组类型,也可以返回这些数据类型。除此之外,PL/pgSQL还可以接收或返回任何自定义的复合数据类型,也支持返回单行记录(record类型)或多行结果集(setof record或table类型)。返回结果集的函数通过执行RETURN NEXT语句生成一条返回的记录(与PostgreSQL不同,HAWQ函数不支持RETURN QUERY语法)。
        PL/pgSQL可以声明输出参数,这种方式可代替用returns语句显式指定返回数据类型的写法。当返回值是单行多列时,用输出参数的方式更方便。

三、给HAWQ内部函数起别名
        许多HAWQ的内部函数是用C语言编写的。这些函数是在HAWQ集群初始化时声明的,并静态连接到HAWQ服务器。用户不能自己定义新的内部函数,但可以给已存在的内部函数起别名。下面的例子创建了一个新的函数fn_all_caps,它是HAWQ的内部函数upper的别名。
create function fn_all_caps (text) returns text as 'upper' language internal strict;
        该函数的调用结果如图3所示。
图3

四、表函数
        表函数返回多行结果集,调用方法就像查询一个from子句中的表、视图或子查询。如果表函数返回单列,那么返回的列名就是函数名。下面是一个表函数的例子,该函数返回channel表中给定ID值的数据。
create function fn_getchannel(int) returns setof channel as $$
    select * from channel where id = $1;
$$ language sql;
        可以使用以下语句调用该函数:
select * from fn_getchannel(-1) as t1;
select * from fn_getchannel(13) as t1;
        调用结果如图4所示。
图4

        与PostgreSQL不同,HAWQ的表函数不能用于表连接。在PostgreSQL中以下查询可以正常执行,如图5所示。
create table t1 (a int);
insert into t1 values (1);
select * from t1,fn_getchannel(13);
图5
        但是在HAWQ中,同样的查询会报如图6所示的错误。
图6
        单独查询表函数是可以的。
create view vw_getchannel as select * from fn_getchannel(13);
select * from vw_getchannel;
        查询结果如图7所示。
图7 

        在某些场景下,函数返回的结果依赖于调用它的参数。为了支持这种情况,表函数可以被声明为返回伪类型(pseudotype)的记录。当这种函数用于查询中时,必须由查询本身指定返回的行结构。下面的例子使用动态SQL,返回结果集依赖于作为入参的查询语句。
create or replace function fn_return_pseudotype ( str_sql text)
 returns setof record as
$$
declare
    v_rec record;
begin
   for v_rec in execute str_sql loop
      return next v_rec;
   end loop;
   return;
end;
$$
language plpgsql;
        调用函数时必须显式指定返回的字段名及其数据类型。
select * from fn_return_pseudotype('select 1') t (id int);
select * from fn_return_pseudotype('select * from channel') t (id int,cname varchar(200),parent_id int);
        查询结果如图8所示。
图8

         https://www.postgresql.org/docs/8.2/static/datatype-pseudo.html显示了PostgreSQL 8.2支持的伪类型。伪类型不能作为表列或变量的数据类型,但可以被用于函数的参数或返回值类型。

五、参数个数可变的函数
        HAWQ从PostgreSQL继承了一个非常好的特性,即函数参数的个数可变。原来做Oracle的时候,想实现这个功能是很麻烦的。参数个数可变是通过一个动态数组实现的,因此所有参数都应该具有相同的数据类型。这种函数将最后一个参数标识为VARIADIC,并且参数必须声明为数组类型。下面是一个例子,实现类似原生函数greatest的功能。
create or replace function fn_mgreatest(variadic numeric[]) returns numeric as $$
declare 
    l_i numeric:=-99999999999999;
    l_x numeric;
    array1 alias for $1;
begin
  for i in array_lower(array1, 1) .. array_upper(array1, 1)
  loop  
    l_x:=array1[i];
    if l_x > l_i then
       l_i := l_x;
	end if;
  end loop;  
  return l_i;  
end;
$$ language 'plpgsql';
        可以使用如下语句执行该函数。
select fn_mgreatest(array[10, -1, 5, 4.4]);
select fn_mgreatest(array[10, -1, 5, 4.4, 100]);
        执行结果如图9所示。


图9


六、多态类型
        PostgreSQL中的anyelement、anyarray、anynonarray和anyenum四种伪类型被称为多态类型。使用这些类型声明的函数叫做多态函数。多态函数的同一参数在每次调用函数时可以有不同数据类型,实际使用的数据类型由调用函数时传入的参数所确定。
        多态参数和返回值是相互绑定的,当一个查询调用多态函数时,特定的数据类型在运行时解析。每个声明为anyelement的位置(参数或返回值)允许是任何实际的数据类型,但是在任何一次给定的调用中,anyelement必须具有相同的实际数据类型。同样,每个声明为anyarray的位置允许是任何实际的数组数据类型,但是在任何一次给定的调用中,anyarray也必须具有相同类型。如果某些位置声明为anyarray,而另外一些位置声明为anyelement,那么实际的数组元素类型必须与anyelement的实际数据类型相同。
        anynonarray在操作上与anyelement完全相同,它只是在anyelement的基础上增加了一个额外约束,即实际类型不能是数组。anyenum在操作上也与anyelement完全相同,它只是在anyelement的基础上增加了一个额外约束,即实际类型必须是枚举(enum)类型。anynonarray和anyenum并不是独立的多态类型,它们只是在anyelement上增加了约束而已。例如,f(anyelement, anyenum)与f(anyenum, anyenum)是等价的,实际参数都必须是同样的枚举类型。
        如果一个函数的返回值被声明为多态类型,那么它的参数中至少应该有一个是多态的,并且参数与返回结果的实际数据类型必须匹配。例如,函数声明为assubscript(anyarray, integer) returns anyelement。此函数的的第一个参数为数组类型,而且返回值必须是实际数组元素的数据类型。再比如一个函数的声明为asf(anyarray) returns anyenum,那么参数只能是枚举类型的数组。
        参数个数可变的函数也可以使用多态类型,实现方式是声明函数的最后一个参数为VARIADIC anyarray。

        例1:判断两个入参是否相等,每次调用的参数类型可以不同,但两个入参的类型必须相同
create or replace function fn_equal (anyelement,anyelement)
    returns boolean as
    $$
begin
    if $1 = $2 then
        return true;
    else
        return false;
    end if;
end;
  $$
language 'plpgsql';
        下列语句调用函数返回情况如图10所示。
select fn_equal(1,1);
select fn_equal(1,'a');
select fn_equal('a','A');
select fn_equal(text 'a',text 'A');
select fn_equal(text 'a',text 'a');
图10
        例2:遍历任意类型的数组,数组元素以行的形式返回。
create or replace function fn_unnest(anyarray)
returns setof anyelement
language 'sql' as
$$
   select $1[i] from generate_series(array_lower($1,1),array_upper($1,1)) i;
$$;
        下列语句调用函数返回情况如图11所示。
select fn_unnest(array[1,2,3,4]);
select fn_unnest(array['a','b','c']);
图11

        例3;新建fn_mgreatest1函数,使它能返回任意数组类型中的最大元素。
create or replace function fn_mgreatest1(v anyelement, variadic anyarray) returns anyelement as $$
declare 
    l_i v%type;
    l_x v%type;
    array1 alias for $2;
begin
    l_i := array1[1];
    for i in array_lower(array1, 1) .. array_upper(array1, 1) loop  
        l_x:=array1[i];
        if l_x > l_i then
           l_i := l_x;
	    end if;
    end loop;  
    return l_i;  
end;
$$ language 'plpgsql';
        说明:
  • 变量不能定义成伪类型,但可以通过参数进行引用,如上面函数中的l_i v%type。
  • 动态数组必须是函数的最后一个参数。
  • 第一个参数的作用仅是为变量定义数据类型,所以在调用函数时传空即可。 
        下列语句调用函数返回情况如图12所示。
select fn_mgreatest1(null, array[10, -1, 5, 4.4]);
select fn_mgreatest1(null, array['a', 'b', 'c']);
图12

七、查看UDF定义
        psql的元命令\df可以查看UDF的定义,返回函数的参数与返回值的类型。用命令行的-E参数,还能够看到元命令对应的对系统表的查询语句。
[gpadmin@hdp3 ~]$ psql -d db1 -E
psql (8.2.15)
Type "help" for help.

db1=# \df
********* QUERY **********
SELECT n.nspname as "Schema",
  p.proname as "Name",
  CASE WHEN p.proretset THEN 'SETOF ' ELSE '' END ||
  pg_catalog.format_type(p.prorettype, NULL) as "Result data type",
  CASE WHEN proallargtypes IS NOT NULL THEN
    pg_catalog.array_to_string(ARRAY(
      SELECT
        CASE
          WHEN p.proargmodes[s.i] = 'i' THEN ''
          WHEN p.proargmodes[s.i] = 'o' THEN 'OUT '
          WHEN p.proargmodes[s.i] = 'b' THEN 'INOUT '
          WHEN p.proargmodes[s.i] = 'v' THEN 'VARIADIC '
        END ||
        CASE
          WHEN COALESCE(p.proargnames[s.i], '') = '' THEN ''
          ELSE p.proargnames[s.i] || ' ' 
        END ||
        pg_catalog.format_type(p.proallargtypes[s.i], NULL)
      FROM
        pg_catalog.generate_series(1, pg_catalog.array_upper(p.proallargtypes, 1)) AS s(i)
    ), ', ')
  ELSE
    pg_catalog.array_to_string(ARRAY(
      SELECT
        CASE
          WHEN COALESCE(p.proargnames[s.i+1], '') = '' THEN ''
          ELSE p.proargnames[s.i+1] || ' '
          END ||
        pg_catalog.format_type(p.proargtypes[s.i], NULL)
      FROM
        pg_catalog.generate_series(0, pg_catalog.array_upper(p.proargtypes, 1)) AS s(i)
    ), ', ')
  END AS "Argument data types",
  CASE
    WHEN p.proisagg THEN 'agg'
    WHEN p.prorettype = 'pg_catalog.trigger'::pg_catalog.regtype THEN 'trigger'
    ELSE 'normal'
  END AS "Type"
FROM pg_catalog.pg_proc p
     LEFT JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace
WHERE pg_catalog.pg_function_is_visible(p.oid)
      AND n.nspname <> 'pg_catalog'
      AND n.nspname <> 'information_schema'
ORDER BY 1, 2, 4;
**************************

                                      List of functions
 Schema |         Name         | Result data type |       Argument data types       |  Type  
--------+----------------------+------------------+---------------------------------+--------
 public | fn_all_caps          | text             | text                            | normal
 public | fn_count_channel     | void             |                                 | normal
 public | fn_equal             | boolean          | anyelement, anyelement          | normal
 public | fn_getchannel        | SETOF channel    | integer                         | normal
 public | fn_mgreatest         | numeric          | variadic numeric[]              | normal
 public | fn_mgreatest1        | anyelement       | v anyelement, variadic anyarray | normal
 public | fn_return_pseudotype | SETOF record     | str_sql text                    | normal
 public | fn_unnest            | SETOF anyelement | anyarray                        | normal
(8 rows)
        可以看到,用户自定义函数包含在pg_proc系统表中,以下语句查看函数体,查询结果如图13所示。
select prosrc from pg_proc where proname='fn_return_pseudotype';
图13

八、删除UDF
        使用drop function <function_name>命令删除函数。注意,在该命令需要加上函数定义的参数类型列表,但不须带参数名。
db1=# drop function fn_mgreatest1;
ERROR:  syntax error at or near ";"
LINE 1: drop function fn_mgreatest1;
                                   ^
db1=# drop function fn_mgreatest1();
ERROR:  function fn_mgreatest1() does not exist
db1=# drop function fn_mgreatest1(anyelement, variadic anyarray);
DROP FUNCTION

九、UDF实例——递归树形遍历
        经常在一个表中有父子关系的两个字段,比如empno与manager,开篇建立的示例表channel也属于这种结构。在Oracle 中可以使用connect by简单解决此类树的遍历问题,PostgreSQL 9也有相似功能的with recursive语法。
with recursive t (id, cname, parent_id, path, depth)  as (
     select id, cname, parent_id, array[id] as path, 1 as depth
     from channel
     where parent_id = -1
     union all
     select  c.id, c.cname, c.parent_id, t.path || c.id, t.depth + 1 as depth
     from channel c
     join t on c.parent_id = t.id
     )
select id, cname, parent_id, path, depth from t
order by path;
        上面的查询在PostgreSQL中的执行结果如图14所示。
图14

        但是,HAWQ不支持with recursive语法,同样的查询,会返回如图15所示的错误。
图15

        我们可以使用HAWQ的递归函数功能,自己编写UDF来实现树的遍历。
        建立函数从某节点向下遍历子节点,递归生成节点信息,函数返回以‘|’作为字段分隔符的字符串:
create or replace function fn_ChildLst(int, int)
returns setof character varying
as
$$
declare
    v_rec character varying;
begin       
    for v_rec in (select case when node = 1 then 
	                          q.id||'|'||q.cname||'|'||q.parent_id||'|'||$2
                         else fn_ChildLst(q.id, $2 + 1)
                         end
                    from (select id, cname, parent_id, node
                            from (select 1 as node
                                  union all
                                  select 2) nodes, channel
                           where parent_id = $1
                           order by id, node) q) loop
        return next v_rec;
    end loop;
    return;
end;
$$
language 'plpgsql';
        建立节点复合数据类型:
create type tp_depth as (rn int, id int, cname varchar(200), parent_id int, depth int);
        将fn_ChildLst函数的返回值转换为tp_depth类型:
create or replace function fn_ChildLst_split(int, int)
returns setof tp_depth
as
$$
    select cast(rownum as int) rn,
           cast(a[1] as int) id, 
           a[2] cname, 
           cast(a[3] as int) parent_id, 
           cast(a[4] as int) depth 
      from (select rownum,string_to_array(fn_ChildLst,'|') a 
              from (select row_number() over() as rownum,* 
                      from fn_ChildLst($1, $2)
                    union all 
                    select 0,id||'|'||cname||'|'||parent_id||'|'||($2 -1) from channel where id = $1) 
            t) t;
$$
language 'sql';
        建立查询结果复合数据类型:
create type tp_result as 
(id int, 
 name1 varchar(1000), 
 parent_id int, 
 depth int,path varchar(200),
 pathname varchar(1000));
        实现类似Oracle SYS_CONNECT_BY_PATH的功能,递归输出某节点id路径:
create or replace function fn_path(a_id integer) 
returns character varying as $$
declare
    v_result character varying;
    v_parent_id int;
begin 
    select t.parent_id into v_parent_id
      from channel as t where t.id = a_id; 
    if found then
        v_result := fn_path(v_parent_id) || '/' || a_id;
    else
        return '';
    end if;
    return v_result; 
end;
$$ language 'plpgsql';
        递归输出某节点的name路径:
create or replace function fn_pathname(a_id integer) 
returns character varying as $$
declare
    v_result character varying;
    v_parent_id int;
 v_cname varchar(200);
 begin 
    select t.cname,t.parent_id into v_cname,v_parent_id
      from channel as t where t.id = a_id; 
    if found then
        v_result := fn_pathname(v_parent_id) || '/' || v_cname;
    else
        return '';
    end if;
    return v_result; 
end;
$$ language 'plpgsql';
        建立输出子节点的函数:
create or replace function fn_showChildLst(int)
returns setof tp_result
as
$$
    select t1.id,
           repeat('  ', t1.depth)||'--'||t1.cname name1,
           t1.parent_id,
           t1.depth,
           fn_path(t1.id) path,
           fn_pathname(t1.id) pathname  
     from fn_ChildLst_split($1,1) t1
    order by t1.rn;
$$
language 'sql';
        使用下面的语句调用函数,结果如图16至图20所示。
select * from fn_showChildLst(-1);
select * from fn_showChildLst(13);
select * from fn_showChildLst(14);
select * from fn_showChildLst(17);
select * from fn_showChildLst(18);
图16


图17


图18


图19


图20

        从某节点向上追溯根节点,递归生成节点信息,函数返回以‘|’作为字段分隔符的字符串:
create or replace function fn_ParentLst(int, int)
returns setof character varying
as
$$
declare
    v_rec character varying;
begin       
    for v_rec in (select case when node = 1 then
                              q.id||'|'||q.cname||'|'||q.parent_id||'|'||$2
                         else fn_ParentLst(q.parent_id, $2 + 1)
                         end
                    from (select id, cname, parent_id, node
                            from (select 1 as node
                                  union all
                                  select 2) nodes, channel
                           where id = $1
                           order by id, node) q) loop
        return next v_rec;
    end loop;
    return;
end;
$$
language 'plpgsql';
        将fn_ParentLst函数的返回值转换为tp_depth类型:
create or replace function fn_ParentLst_split(int, int)
returns setof tp_depth
as
$$
    select cast(rownum as int) rn,
           cast(a[1] as int) id, 
           a[2] cname, 
           cast(a[3] as int) parent_id, 
           cast(a[4] as int) depth 
      from (select rownum,string_to_array(fn_ParentLst,'|') a 
              from (select row_number() over() as rownum,* from fn_ParentLst($1, $2)) t) t;
$$
language 'sql';
        建立输出父节点的函数:
create or replace function fn_showParentLst(int)
returns setof tp_result
as
$$
    select t1.id,
           repeat('  ', t1.depth)||'--'||t1.cname name1,
           t1.parent_id,
           t1.depth,
           fn_path(t1.id) path,
           fn_pathname(t1.id) pathname  
  from fn_ParentLst_split($1,0) t1
 order by t1.rn;
$$
language 'sql';
        使用下面的语句调用函数,结果如图21至图25所示。
select * from fn_showParentLst(-1);
select * from fn_showParentLst(13);
select * from fn_showParentLst(14);
select * from fn_showParentLst(17);
select * from fn_showParentLst(18);
图21


图22


图23


图24


图25


参考:
MySQL实现树的遍历
PostgreSQL 8.4: preserving order for hierarchical query
PostgreSQL: function 返回结果集多列和单列的例子
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
sdk LCS/Telegraphics Wintab* Interface Specification 1.1: 16- and 32-bit API Reference By Rick Poyner Revised February 11, 2012 This specification was developed in response to a perceived need for a standardized programming inter-face to digitizing tablets, three dimensional position sensors, and other pointing devices by a group of lead-ing digitizer manufacturers and applications developers. The availability of drivers that support the features of the specification will simplify the process of developing Windows appli¬cation programs that in-corporate absolute coordinate input, and enhance the acceptance of ad¬vanced pointing de¬vices among users. This specification is intended to be an open standard, and as such the text and information contained herein may be freely used, copied, or distributed without compensation or licensing restrictions. This document is copyright 1991-2012 by LCS/Telegraphics.* Address questions and comments to: LCS/Telegraphics 150 Rogers St. Cambridge, MA 02142 (617)225-7970 (617)225-7969 FAX Compuserve: 76506,1676 Internet: [email protected] Note: sections marked with the “(1.1)” are new sections added for specification version 1.1. Sec-tions bearing the “(1.1 modified)” notation contain updated information for specification version 1.1. Version 1.1 Update Notation Conventions 1 1. Background Information 1 1.1. Features of Digitizers 1 1.2. The Windows Environment 1 2. Design Goals 2 2.1. User Control 2 2.2. Ease of Programming 2 2.3. Tablet Sharing 3 2.4. Tablet Feature Support 3 3. Design Concepts 3 3.1. Device Conventions 3 3.2. Device Information 4 3.3. Tablet Contexts 4 3.4. Event Packets 4 3.5. Tablet Managers 5 3.6. Extensions 5 3.7. Persistent Binding of Interface Features (1.1) 6 4. Interface Implementations 6 4.1. File and Module Conventions 6 4.2. Feature Support Options 6 5. Function Reference 7 5.1. Basic Functions 7 5.1.1. WTInfo 8 5.1.2. WTOpen 9 5.1.3. WTClose 10 5.1.4. WTPacketsGet 10 5.1.5. WTPacket 11 5.2. Visibility Functions 11 5.2.1. WTEnable 11 5.2.2. WTOverlap 12 5.3. Context Editing Functions 12 5.3.1. WTConfig 12 5.3.2. WTGet 13 5.3.3. WTSet (1.1 modified) 13 5.3.4. WTExtGet 14 5.3.5. WTExtSet 14 5.3.6. WTSave 15 5.3.7. WTRestore 15 5.4. Advanced Packet and Queue Functions 16 5.4.1. WTPacketsPeek 16 5.4.2. WTDataGet 17 5.4.3. WTDataPeek 17 5.4.4. WTQueuePackets (16-bit only) 18 5.4.5. WTQueuePacketsEx 18 5.4.6. WTQueueSizeGet 19 5.4.7. WTQueueSizeSet 19 5.5. Manager Handle Functions 19 5.5.1. WTMgrOpen 19 5.5.2. WTMgrClose 20 5.6. Manager Context Functions 20 5.6.1. WTMgrContextEnum 20 5.6.2. WTMgrContextOwner 21 5.6.3. WTMgrDefContext 22 5.6.4. WTMgrDefContextEx (1.1) 22 5.7. Manager Configuration Functions 23 5.7.1. WTMgrDeviceConfig 23 5.7.2. WTMgrConfigReplace (16-bit only) 24 5.7.3. WTMgrConfigReplaceEx 24 5.8. Manager Packet Hook Functions 25 5.8.1. WTMgrPacketHook (16-bit only) 26 5.8.2. WTMgrPacketHookEx 26 5.8.3. WTMgrPacketUnhook 29 5.8.4. WTMgrPacketHookDefProc (16-bit only) 30 5.8.5. WTMgrPacketHookNext 30 5.9. Manager Preference Data Functions 31 5.9.1. WTMgrExt 31 5.9.2. WTMgrCsrEnable 32 5.9.3. WTMgrCsrButtonMap 32 5.9.4. WTMgrCsrPressureBtnMarks (16-bit only) 33 5.9.5. WTMgrCsrPressureBtnMarksEx 33 5.9.6. WTMgrCsrPressureResponse 34 5.9.7. WTMgrCsrExt 35 6. Message Reference 36 6.1. Event Messages 36 6.1.1. WT_PACKET 36 6.1.2. WT_CSRCHANGE (1.1) 37 6.2. Context Messages 37 6.2.1. WT_CTXOPEN 37 6.2.2. WT_CTXCLOSE 37 6.2.3. WT_CTXUPDATE 38 6.2.4. WT_CTXOVERLAP 38 6.2.5. WT_PROXIMITY 38 6.3. Information Change Messages 39 6.3.1. WT_INFOCHANGE 39 7. Data Reference 39 7.1. Common Data Types (1.1 modified) 39 7.2. Information Data Structures 41 7.2.1. AXIS 41 7.2.2. Information Categories and Indices (1.1 modified) 42 7.3. Context Data Structures 50 7.3.1. LOGCONTEXT (1.1 modified) 50 7.4. Event Data Structures 55 7.4.1. PACKET (1.1 modified) 55 7.4.2. ORIENTATION 57 7.4.3. ROTATION (1.1) 58 Appendix A. Using PKTDEF.H 59 Appendix B. Extension Definitions 60 B.1. Extensions Programming 60 B.2. Out of Bounds Tracking 61 OBT Programming 61 Information Category 61 Turning OBT On and Off 61 B.3. Function Keys 62 FKEYS Programming 62 Information Category 62 B.4. Tilt 62 TILT Programming 63 Information Category 63 B.5. Cursor Mask 63 CSRMASK Programming 64 Information Category 64 B.6. Extended Button Masks 64 XBTNMASK Programming 64 Information Category 65 VERSION 1.1 UPDATE NOTATION CONVENTIONS Sections marked with the “(1.1)” are new sections added for specification version 1.1. Sections bearing the “(1.1 modified)” notation contain updated information for specification version 1.1. The “(1.1)” notation also marks the definitions of new functions, messages, and data structures. The nota-tion “1.1:” marks new text or commentaries explaining new functionality added to existing features. 1 BACKGROUND INFORMATION This document describes a programming interface for using digitizing tablets and other advanced pointing de¬vices with Microsoft Windows Version 3.0 and above. The design presented here is based on the input of numerous professionals from the pointing device manufacturing and Windows soft¬ware development industries. In this document, the words "tablet" and "digitizer" are used interchange¬ably to mean all absolute point¬ing or digitizing devices that can be made to work with this interface. The definition is not lim¬ited to de¬vices that use a physical tablet. In fact, this specification can support de¬vices that combine rela¬tive and absolute pointing as well as purely relative devices. The following sections describe features of tablets and of the Windows environment that helped mo¬tivate the design. 1.1 Features of Digitizers Digitizing tablets present several problems to device interface authors. • Many tablets have a very high report rate. • Many tablets have many configurable features and types of input information. • Tablets often control the system cursor, provide additional digitizing input, and provide template or macro functions. 1.2 The Windows Environment Programming for tablets in the Windows environment presents additional problems. • Multitasking means multiple applications may have to share the tablet. • The tablet must also be able to control the system cursor and/or the pen (in Pen Windows). • The tablet must work with legacy applications, and with applications written to take advan¬tage of tablet services. • The tablet driver must add minimal speed and memory overhead, so as many applications as possible can run as efficiently as possible. • The user should be able to control how applications use the tablet. The user interface must be ef-ficient, consistent, and customizable. 2 DESIGN GOALS While the tablet interface design must address the technical problems stated above, it must also be useful to the programmers who will write tablet programs, and ultimately, to the tablet users. Four design goals will help clarify these needs, and provide some criteria for evaluating the interface speci¬fication. The goals are user control, ease of programming, tablet sharing, and tablet feature support. 2.1 User Control The user should be able to use and control the tablet in as natural and easy a manner as possible. The user's preferences should take precedence over application requests, where possible. Here are questions to ask when thinking about user control as a design goal: • Can the user understand how applications use the tablet? • Is the interface for controlling tablet functions natural and unobtrusive? • Is the user allowed to change things that help to customize the work environment, but pre¬vented from changing things over which applications must have control? 2.2 Ease of Programming Programming is easiest when the amount of knowledge and effort required matches the task at hand. Writing simple programs should require only a few lines of code and a minimal understanding of the en-vironment. On the other hand, more advanced features and functions should be available to those who need them. The interface should accommodate three kinds of programmers: those who wish to write sim-ple tablet programs, programmers who wish to write complex applications that take full ad¬vantage of tab-let capabilities, and programmers who wish to provide tablet device control features. In addition, the inter-face should accommodate programmers in as many different programming lan¬guages, situations, and en-vironments as possible. Questions to ask when thinking about ease of programming include: • How hard is it to learn the interface and write a simple program that uses tablet input? • Can programmers of complex applications control the features they need? • Are more powerful tablet device control features available? • Can the interface be used in different programming environments? • Is the interface logical, consistent, and robust? 2.3 Tablet Sharing In the Windows environment, multiple applications that use the tablet may be running at once. Each ap-plication will require different services. Applications must be able to get the services they need without getting in each others' way. Questions to ask when thinking about tablet sharing include: • Can tablet applications use the tablet features they need, independent of other applications? • Does the interface prevent a rogue application from "hijacking" the tablet, or causing dead¬locks? • Does the sharing architecture promote efficiency? 2.4 Tablet Feature Support The interface gives standard access to as many features as possible, while leaving room for future ex¬ten-sions and vendor-specific customizations. Applications should be able to get the tablet informa¬tion and services they want, just the way they want them. Users should be able to use the tablet to set up an effi-cient, comfortable work environment. Questions to ask when thinking about tablet feature support include: • Does the interface provide the features applications need? Are any commonly available fea¬tures not supported? • Does the interface provide what users need? Is anything missing? • Are future extensions possible and fairly easy? • Are vendor-specific extensions possible? 3 DESIGN CONCEPTS The proposed interface design depends on several fundamental concepts. Devices and cursor types de-scribe physical hardware configurations. The interface publishes read-only information through a single information interface. Applications interact with the interface by setting up tablet contexts and consuming event packets. Applications may assume interface and hardware control functions by be¬coming tablet managers. The interface provides explicit support for future extensions. 3.1 Device Conventions The interface provides access to one or more devices that produce pointing input. Devices sup¬ported by this interface have some common characteristics. The device must define an absolute or relative coordi-nate space in at least two dimensions for which it can return position data. The device must have a point-ing ap¬para¬tus or method (such as a stylus, or a finger touching a touch pad), called the cursor, that de¬fines the current position. The cursor must be able to return at least one bit of additional state (via a but¬ton, touching a digitizing surface, etc.). Devices may have multiple cursor types that have different physical configurations, or that have differ¬ent numbers of buttons, or return auxiliary information, such as pressure information. Cursor types may also describe different optional hardware configurations. The interface defines a standard orientation for reporting device native coordinates. When the user is viewing the device in its normal position, the coordinate origin will be at the lower left of the device. The coordinate system will be right-handed, that is, the positive x axis points from left to right, and the posi¬tive y axis points either upward or away from the user. The z axis, if supported, points either to¬ward the user or upward. For devices that lay flat on a table top, the x-y plane will be horizontal and the z axis will point upward. For devices that are oriented vertically (for example, a touch screen on a conventional dis¬play), the x-y plane will be vertical, and the z axis will point toward the user. 3.2 Device Information Any program can get descriptive information about the tablet via the WTInfo function. The interface specifies certain information that must be available, but allows new implementations to add new types of information. The basic information includes device identifiers, version numbers, and overall ca¬pabilities. The information items are organized by category and index numbers. The combination of a category and index specifies a single information data item, which may be a scalar value, string, structure, or array. Applica¬tions may retrieve single items or whole categories at once. Some categories are multiplexed. A single category code represents the first of a group of identically in-dexed categories, one for each of a set of similar objects. Multiplexed categories in¬clude those for devices and cur¬sor types. One constructs the category number by adding the defined cate¬gory code to a zero-based device or cursor identification number. The information is read-only for normal tablet applications. Some information items may change during the course of a Windows session; tablet applications receive messages notifying them of changes in tablet information. 3.3 Tablet Contexts Tablet contexts play a central role in the interface; they are the objects that applications use to specify their use of the tablet. Con¬texts include not only the physical area of the tablet that the application will use, but also information about the type, con¬tents, and delivery method for tablet events, as well as other information. Tablet contexts are somewhat analo¬gous to display contexts in the GDI interface model; they contain context information about a spe¬cific application's use of the tablet. An application can open more than one context, but most only need one. Applications can customize their contexts, or they can open a context using a default context specification that is always available. The WTInfo function provides access to the default context specification. Opening a context requires a window handle. The window handle becomes the context's owner and will receive any window messages associated with the context. Contexts are remotely similar to screen windows in that they can physically overlap. The tablet inter¬face uses a combination of context overlap order and context attributes to decide which context will process a given event. The topmost context in the overlap order whose input context encompasses the event, and whose event masks select the event, will process the event. (Note that the notion of overlap order is sepa-rate from the notion of the physical z dimension.) Tablet managers (described below) provide a way to modify and overlap contexts. 3.4 Event Packets Tablet contexts generate and report tablet activity via event packets. Applications can control how they receive events, which events they receive, and what information they contain. Applications may receive events either by polling, or via Windows messages. • Polling: Any application that has opened a context can call the WTPacketsGet function to get the next state of the tablet for that context. • Window Messages: Applications that request messages will receive the WT_PACKET mes¬sage (described below), which indicates that something happened in the context and provides a refer-ence to more information. Applications can control which events they receive by using event masks. For example, some appli¬ca¬tions may only need to know when a button is pressed, while others may need to receive an event every time the cursor moves. Tablet context event masks implement this type of control. Applications can control the contents of the event packets they receive. Some tablets can return data that many applications will not need, like button pressure and three dimensional position and orien¬tation in-formation. The context object provides a way of specifying which data items the appli¬cation needs. This allows the driver to improve the efficiency of packet delivery to applications that only need a few items per packet. Packets are stored in context-specific packet queues and retrieved by explicit function calls. The interface provides ways to peek at and get packets, to query the size and contents of the queue, and to re-size the queue. 3.5 Tablet Managers The interface provides functions for tablet management. An application can become a tablet manager by opening a tablet manager handle. This handle allows the manager access to spe¬cial functions. These man-agement functions allow the application to arrange, overlap, and modify tablet contexts. Man¬agers may also perform other functions, such as changing default values used by applica¬tions, chang¬ing ergo¬nomic, preference, and configuration settings, controlling tablet behavior with non-tablet aware applica¬tions, modi¬fy¬ing user dialogs, and recording and playing back tablet packets. Opening a manager handle re¬quires a window handle. The window becomes a manager window and receives window messages about interface and con¬text activity. 3.6 Extensions The interface allows implementations to define additional features called extensions. Extensions can be made available to new applications without the need to modify ex¬isting applications. Extensions are sup-ported through the information categories, through the flexible definition of packets, and through special context and manager functions. Designing an extension involves defining the meaning and behavior of the extension packet and/or prefer-ence data, filling in the information category, defining the extension's interface with the special functions, and possibly defining additional functions to support the extension. Each extension will be assigned a unique tag for identification. Not all implementations will support all extensions. A multiplexed information category contains descriptive data about extensions. Note that applica¬tions must find their extensions by iterating through the categories and matching tags. While tags are fixed across all implementations, category numbers may vary among implementations. 3.7 Persistent Binding of Interface Features (1.1) The interface provides access to many of its features using consecutive numeric indices whose value is not guaranteed from session to session. However, sufficient information is provided to create unique identifi¬ers for devices, cursors, and interface extensions. Devices should be uniquely identified by the contents of their name strings. If multiple identical devices are present, implementation providers should provide unique, persistent id strings to the extent possible. Identical devices that return unique serial numbers are ideal. If supported by the hardware, cursors also may have a physical cursor id that uniquely identifies the cursor in a persistent and stable manner. Interface extensions are uniquely identified by their tag. 4 INTERFACE IMPLEMENTATIONS Implementations of this interface usually support one specific device, a class of similar devices, or a com-mon combination of devices. The following sections discuss guidelines for implementations. 4.1 File and Module Conventions For 16-bit implementations, the interface functions, and any additional vendor- or device-specific func-tions, reside in a dynamic link library with the file name "WINTAB.DLL" and module name "WINTAB"; 32-bit implementations use the file name "WINTAB32.DLL" and module name "WINTAB32." Any other file or module con¬ventions are implementation specific. Implementations may include other library mod-ules or data files as necessary. Installation processes are likewise implementa¬tion-specific. Wintab programs written in the C language require two header files. WINTAB.H contains definitions of all of the functions, constants, and fixed data types. PKTDEF.H contains a parameterized definition of the PACKET data structure, that can be tailored to fit the application. The Wintab Programmer's Kit con¬tains these and other files necessary for Wintab programming, plus several example programs with C-lan¬guage source files. The Wintab Programmer's Kit is available from the author. 4.2 Feature Support Options Some features of the interface are optional and may be left out by some implementations. Support of defined data items other than x, y, and buttons is optional. Many devices only report x, y, and button information. Support of system-cursor contexts is optional. This option relieves implementations of replacing the sys¬tem mouse driver in Windows versions before 3.1. Support of Pen Windows contexts is optional. Not all systems will have the Pen Windows hardware and software necessary. Support of external tablet manager applications is optional, and the number of manager handles is imple-mentation-dependent. However, the manager functions should be present in all implementa¬tions, return¬ing appropriate failure codes if not fully implemented. An implementation may provide context- and hardware-management support internally only, if desired. On the other hand, providing the external man-ager interface may relieve the implementation of a considerable amount of user in¬terface code, and make improvements to the manager interface easier to implement and distribute later. Support of extension data items is optional. Most extensions will be geared to unusual hardware features. 5 FUNCTION REFERENCE All tablet function names have the prefix "WT" and have attributes equivalent to WINAPI. Applica¬tions gain access to the tablet interface functions through a dynamic-link library with standard file and module names, as defined in the previous section. Applications may link to the functions by using the Windows functions LoadLibrary, FreeLibrary, and GetProcAddress, or use an import library. Specific to 32-bit Wintab: The functions WTInfo, WTOpen, WTGet, and WTSet have both ANSI and Unicode versions, using the same ANSI/Unicode porting conventions used in the Win32 API. Five non-portable functions, WTQueuePackets, WTMgrCsrPressureBtnMarks, WTMgrConfigReplace, WTMgrPacketHook, and WTMgrPacketHookDefProc are replaced by new portable functions WTQueuePacketsEx, WTMgrCsrPressureBtnMarksEx, WTMgrConfigReplaceEx, WTMgrPack-etHookEx, WTMgrPacketUnhook, and WTMgrPacketHookNext. WTMgrConfigReplaceEx and WTMgrPacketHookEx have both ANSI and Unicode versions. Table 5.1. Ordinal Function Numbers for Dynamic Linking Ordinal numbers for dynamic linking are defined in the table below. Where two ordinal entries appear, the first entry identifies the 16-bit and 32-bit ANSI versions of the function. The second entry identifies the 32-bit Unicode version. Function Name Ordinal Function Name Ordinal WTInfo 20, 1020 WTMgrOpen 100 WTOpen 21, 1021 WTMgrClose 101 WTClose 22 WTMgrContextEnum 120 WTPacketsGet 23 WTMgrContextOwner 121 WTPacket 24 WTMgrDefContext 122 WTEnable 40 WTMgrDefContextEx (1.1) 206 WTOverlap 41 WTMgrDeviceConfig 140 WTConfig 60 WTMgrConfigReplace 141 WTGet 61, 1061 WTMgrConfigReplaceEx 202, 1202 WTSet 62, 1062 WTMgrPacketHook 160 WTExtGet 63 WTMgrPacketHookEx 203, 1203 WTExtSet 64 WTMgrPacketUnhook 204 WTSave 65 WTMgrPacketHookDefProc 161 WTRestore 66 WTMgrPacketHookNext 205 WTPacketsPeek 80 WTMgrExt 180 WTDataGet 81 WTMgrCsrEnable 181 WTDataPeek 82 WTMgrCsrButtonMap 182 WTQueuePackets 83 WTMgrCsrPressureBtnMarks 183 WTQueuePacketsEx 200 WTMgrCsrPressureBtnMarksEx 201 WTQueueSizeGet 84 WTMgrCsrPressureResponse 184 WTQueueSizeSet 85 WTMgrCsrExt 185 5.1 Basic Functions The functions in the following section will be used by most tablet-aware applications. They include getting interface and device information, opening and closing contexts, and retrieving packets by polling or via Windows messages. 5.1.1 WTInfo Syntax UINT WTInfo(wCategory, nIndex, lpOutput) This function returns global information about the interface in an application-sup-plied buffer. Different types of information are specified by different index argu-ments. Applications use this function to receive information about tablet coordi-nates, physical dimensions, capabilities, and cursor types. Parameter Type/Description wCategory UINT Identifies the category from which information is being re-quested. nIndex UINT Identifies which information is being requested from within the category. lpOutput LPVOID Points to a buffer to hold the requested information. Return Value The return value specifies the size of the returned information in bytes. If the infor-mation is not supported, the function returns zero. If a tablet is not physi¬cally pres-ent, this function always returns zero. Comments Several important categories of information are available through this function. First, the function provides identification information, including specification and software version numbers, and tablet vendor and model information. Sec¬ond, the function provides general capability information, including dimensions, resolutions, optional features, and cursor types. Third, the function provides categories that give defaults for all tablet context attributes. Finally, the func¬tion may provide any other implementation- or vendor-specific information cat¬egories necessary. The information returned by this function is subject to change during a Win¬dows session. Applications cannot change the information returned here, but tablet man-ager applications or hardware changes or errors can. Applications can respond to information changes by fielding the WT_INFOCHANGE message. The parameters of the message indicate which information has changed. If the wCategory argument is zero, the function copies no data to the output buffer, but returns the size in bytes of the buffer necessary to hold the largest complete category. If the nIndex argument is zero, the function returns all of the information entries in the category in a single data structure. If the lpOutput argument is NULL, the function just returns the required buffer size. See Also Category and index definitions in tables 7.3 through 7.9, and the WT_INFOCHANGE message in section 6.3.1. 5.1.2 WTOpen Syntax HCTX WTOpen(hWnd, lpLogCtx, fEnable) This function establishes an active context on the tablet. On successful comple¬tion of this function, the application may begin receiving tablet events via mes¬sages (if they were requested), and may use the handle returned to poll the con¬text, or to per-form other context-related functions. Parameter Type/Description hWnd HWND Identifies the window that owns the tablet context, and receives messages from the context. lpLogCtx LPLOGCONTEXT Points to an application-provided LOGCONTEXT data structure describing the context to be opened. fEnable BOOL Specifies whether the new context will immediately begin processing input data. Return Value The return value identifies the new context. It is NULL if the context is not opened. Comments Opening a new context allows the application to receive tablet input or creates a context that controls the system cursor or Pen Windows pen. The owning window (and all manager windows) will immediately receive a WT_CTXOPEN message when the context has been opened. If the fEnable argument is zero, the context will be created, but will not process input. The context can be enabled using the WTEnable function. If tablet event messages were requested in the context specification, the owning window will receive them. The application can control the message numbers used the lcMsgBase field of the LOGCONTEXT structure. The window that owns the new context will receive context and information change messages even if event messages were not requested. It is not necessary to handle these in many cases, but some applications may wish to do so. The newly opened tablet context will be placed on the top of the context overlap or-der. Invalid or out-of-range attribute values in the logical context structure will ei¬ther be validated, or cause the open to fail, depending on the attributes involved. Upon a successful return from the function, the context specification pointed to by lpLogCtx will contain the validated values. See Also The WTEnable function in section 5.2.1, the LOGCONTEXT data structure in section 7.3.1, and the context and infor¬mation change messages in sections 6.2 and 6.3. 5.1.3 WTClose Syntax BOOL WTClose(hCtx) This function closes and destroys the tablet context object. Parameter Type/Description hCtx HCTX Identifies the context to be closed. Return Value The function returns a non-zero value if the context was valid and was destroyed. Otherwise, it returns zero. Comments After a call to this function, the passed handle is no longer valid. The owning win¬dow (and all manager windows) will receive a WT_CTXCLOSE message when the context has been closed. See Also The WTOpen function in section 5.1.2. 5.1.4 WTPacketsGet Syntax int WTPacketsGet(hCtx, cMaxPkts, lpPkts) This function copies the next cMaxPkts events from the packet queue of context hCtx to the passed lpPkts buffer and removes them from the queue. Parameter Type/Description hCtx HCTX Identifies the context whose packets are being returned. cMaxPkts int Specifies the maximum number of packets to return. lpPkts LPVOID Points to a buffer to receive the event packets. Return Value The return value is the number of packets copied in the buffer. Comments The exact structure of the returned packet is determined by the packet infor¬mation that was requested when the context was opened. The buffer pointed to by lpPkts must be at least cMaxPkts * sizeof(PACKET) bytes long to prevent overflow. Applications may flush packets from the queue by calling this function with a NULL lpPkt argument. See Also The WTPacketsPeek function in section 5.4.1, and the descriptions of the LOGCONTEXT (section 7.3.1) and PACKET (section 7.4.1) data structures. 5.1.5 WTPacket Syntax BOOL WTPacket(hCtx, wSerial, lpPkt) This function fills in the passed lpPkt buffer with the context event packet having the specified serial number. The returned packet and any older packets are removed from the context's internal queue. Parameter Type/Description hCtx HCTX Identifies the context whose packets are being returned. wSerial UINT Serial number of the tablet event to return. lpPkt LPVOID Points to a buffer to receive the event packet. Return Value The return value is non-zero if the specified packet was found and returned. It is zero if the specified packet was not found in the queue. Comments The exact structure of the returned packet is determined by the packet infor¬mation that was requested when the context was opened. The buffer pointed to by lpPkts must be at least sizeof(PACKET) bytes long to pre-vent overflow. Applications may flush packets from the queue by calling this function with a NULL lpPkts argument. See Also The descriptions of the LOGCONTEXT (section 7.3.1) and PACKET (section 7.4.1) data structures. 5.2 Visibility Functions The functions in this section allow applications to control contexts' visibility, whether or not they are pro-cessing input, and their overlap order. 5.2.1 WTEnable Syntax BOOL WTEnable(hCtx, fEnable) This function enables or disables a tablet context, temporarily turning on or off the processing of packets. Parameter Type/Description hCtx HCTX Identifies the context to be enabled or disabled. fEnable BOOL Specifies enabling if non-zero, disabling if zero. Return Value The function returns a non-zero value if the enable or disable request was satis¬fied, zero otherwise. Comments Calls to this function to enable an already enabled context, or to disable an al¬ready disabled context will return a non-zero value, but otherwise do nothing. The context’s packet queue is flushed on disable. Applications can determine whether a context is currently enabled by using the WTGet function and examining the lcStatus field of the LOGCONTEXT struc¬ture. See Also The WTGet function in section 5.3.2, and the LOGCONTEXT structure in sec¬tion 7.3.1. 5.2.2 WTOverlap Syntax BOOL WTOverlap(hCtx, fToTop) This function sends a tablet context to the top or bottom of the order of over¬lapping tablet contexts. Parameter Type/Description hCtx HCTX Identifies the context to move within the overlap order. fToTop BOOL Specifies sending the context to the top of the overlap or-der if non-zero, or to the bottom if zero. Return Value The function returns non-zero if successful, zero otherwise. Comments Tablet contexts' input areas are allowed to overlap. The tablet interface main¬tains an overlap order that helps determine which context will process a given event. The topmost context in the overlap order whose input context encom¬passes the event, and whose event masks select the event will process the event. This function is useful for getting access to input events when the application's con-text is overlapped by other contexts. The function will fail only if the context argument is invalid. 5.3 Context Editing Functions This group of functions allows applications to edit, save, and restore contexts. 5.3.1 WTConfig Syntax BOOL WTConfig(hCtx, hWnd) This function prompts the user for changes to the passed context via a dialog box. Parameter Type/Description hCtx HCTX Identifies the context that the user will modify via the dialog box. hWnd HWND Identifies the window that will be the parent window of the dialog box. Return Value The function returns a non-zero value if the tablet context was changed, zero oth-erwise. Comments Tablet applications can use this function to let the user choose context attributes that the application doesn't need to control. Applications can control the editing of con¬text attributes via the lcLocks logical context structure member. Applications should consider providing access to this function through a menu item or command. See Also The LOGCONTEXT structure in section 7.3.1 and the context lock values in table 7.13. 5.3.2 WTGet Syntax BOOL WTGet(hCtx, lpLogCtx) This function fills the passed structure with the current context attributes for the passed handle. Parameter Type/Description hCtx HCTX Identifies the context whose attributes are to be copied. lpLogCtx LPLOGCONTEXT Points to a LOGCONTEXT data structure to which the context attributes are to be copied. Return Value The function returns a non-zero value if the data is retrieved successfully. Oth¬er¬wise, it returns zero. See Also The LOGCONTEXT structure in section 7.3.1. 5.3.3 WTSet (1.1 modified) Syntax BOOL WTSet(hCtx, lpLogCtx) This function allows some of the context's attributes to be changed on the fly. Parameter Type/Description hCtx HCTX Identifies the context whose attributes are being changed. lpLogCtx LPLOGCONTEXT Points to a LOGCONTEXT data structure containing the new context attributes. Return Value The function returns a non-zero value if the context was changed to match the passed context specification; it returns zero if any of the requested changes could not be made. Comments If this function is called by the task or process that owns the context, any context attribute may be changed. Otherwise, the function can change attributes that do not affect the format or meaning of the context's event packets and that were not speci-fied as locked when the context was opened. Context lock values can only be changed by the context’s owner. 1.1: If the hCtx argument is a default context handle returned from WTMgrDef-Context or WTMgrDefContextEx, and the lpLogCtx argument is WTP_LPDEFAULT, the default context will be reset to its initial factory default values. See Also The LOGCONTEXT structure in section 7.3.1 and the context lock values in table 7.13. 5.3.4 WTExtGet Syntax BOOL WTExtGet(hCtx, wExt, lpData) This function retrieves any context-specific data for an extension. Parameter Type/Description hCtx HCTX Identifies the context whose extension attributes are being retrieved. wExt UINT Identifies the extension tag for which context-specific data is being retrieved. lpData LPVOID Points to a buffer to hold the retrieved data. Return Value The function returns a non-zero value if the data is retrieved successfully. Oth¬er¬wise, it returns zero. See Also The extension definitions in Appendix B. 5.3.5 WTExtSet Syntax BOOL WTExtSet(hCtx, wExt, lpData) This function sets any context-specific data for an extension. Parameter Type/Description hCtx HCTX Identifies the context whose extension attributes are being modified. wExt UINT Identifies the extension tag for which context-specific data is being modified. lpData LPVOID Points to the new data. Return Value The function returns a non-zero value if the data is modified successfully. Oth¬er¬wise, it returns zero. Comments Extensions may forbid their context-specific data to be changed during the life¬time of a context. For such extensions, calls to this function would always fail. Extensions may also limit context data editing to the task of the owning window, as with the context locks. See Also The extension definitions in Appendix B, the LOGCONTEXT data structure in section 7.3.1 and the context locking values in table 7.13. 5.3.6 WTSave Syntax BOOL WTSave(hCtx, lpSaveInfo) This function fills the passed buffer with binary save information that can be used to restore the equivalent context in a subsequent Windows session. Parameter Type/Description hCtx HCTX Identifies the context that is being saved. lpSaveInfo LPVOID Points to a buffer to contain the save information. Return Value The function returns non-zero if the save information is successfully retrieved. Oth-erwise, it returns zero. Comments The size of the save information buffer can be determined by calling the WTInfo function with category WTI_INTERFACE, index IFC_CTXSAVESIZE. The save information is returned in a private binary data format. Applications should store the information unmodified and recreate the context by passing the save information to the WTRestore function. Using WTSave and WTRestore allows applications to easily save and restore ex-tension data bound to contexts. See Also The WTRestore function in section 5.3.7. 5.3.7 WTRestore Syntax HCTX WTRestore(hWnd, lpSaveInfo, fEnable) This function creates a tablet context from save information returned from the WTSave function. Parameter Type/Description hWnd HWND Identifies the window that owns the tablet context, and receives messages from the context. lpSaveInfo LPVOID Points to a buffer containing save information. fEnable BOOL Specifies whether the new context will immediately begin processing input data. Return Value The function returns a valid context handle if successful. If a context equivalent to the save information could not be created, the function returns NULL. Comments The save information is in a private binary data format. Applications should only pass save information retrieved by the WTSave function. This function is much like WTOpen, except that it uses save in¬formation for input instead of a logical context. In particular, it will generate a WT_CTXOPEN mes¬sage for the new context. See Also The WTOpen function in section 5.1.2, the WTSave function in section 5.3.6, and the WT_CTXOPEN message in section 6.2.1. 5.4 Advanced Packet and Queue Functions These functions provide advanced packet retrieval and queue manipulation. The packet retrieval functions require the application to provide a packet output buffer. To prevent overflow, the buffer must be large enough to hold the requested number of packets from the specified context. It is up to the caller to deter¬mine the packet size (by interrogating the context, if necessary), and to allocate a large enough buffer. Ap¬plications may flush packets from the queue by passing a NULL buffer pointer. 5.4.1 WTPacketsPeek Syntax int WTPacketsPeek(hCtx, cMaxPkts, lpPkts) This function copies the next cMaxPkts events from the packet queue of context hCtx to the passed lpPkts buffer without removing them from the queue. Parameter Type/Description hCtx HCTX Identifies the context whose packets are being read. cMaxPkts int Specifies the maximum number of packets to return. lpPkts LPVOID Points to a buffer to receive the event packets. Return Value The return value is the number of packets copied in the buffer. Comments The buffer pointed to by lpPkts must be at least cMaxPkts * sizeof(PACKET) bytes long to prevent overflow. See Also the WTPacketsGet function in section 5.1.4. 5.4.2 WTDataGet Syntax int WTDataGet(hCtx, wBegin, wEnd, cMaxPkts, lpPkts, lpNPkts) This function copies all packets with serial numbers between wBegin and wEnd in-clusive from the context's queue to the passed buffer and removes them from the queue. Parameter Type/Description hCtx HCTX Identifies the context whose packets are being returned. wBegin UINT Serial number of the oldest tablet event to return. wEnd UINT Serial number of the newest tablet event to return. cMaxPkts int Specifies the maximum number of packets to return. lpPkts LPVOID Points to a buffer to receive the event packets. lpNPkts LPINT Points to an integer to receive the number of packets ac-tually copied. Return Value The return value is the total number of packets found in the queue between wBegin and wEnd. Comments The buffer pointed to by lpPkts must be at least cMaxPkts * sizeof(PACKET) bytes long to prevent overflow. See Also The WTDataPeek function in section 5.4.3, and the WTQueuePacketsEx function in section 5.4.5. 5.4.3 WTDataPeek Syntax int WTDataPeek(hCtx, wBegin, wEnd, cMaxPkts, lpPkts, lpNPkts) This function copies all packets with serial numbers between wBegin and wEnd in-clusive, from the context's queue to the passed buffer without removing them from the queue. Parameter Type/Description hCtx HCTX Identifies the context whose packets are being read. wBegin UINT Serial number of the oldest tablet event to return. wEnd UINT Serial number of the newest tablet event to return. cMaxPkts int Specifies the maximum number of packets to return. lpPkts LPVOID Points to a buffer to receive the event packets. lpNPkts LPINT Points to an integer to receive the number of packets ac-tually copied. Return Value The return value is the total number of packets found in the queue between wBegin and wEnd. Comments The buffer pointed to by lpPkts must be at least cMaxPkts * sizeof(PACKET) bytes long to prevent overflow. See Also The WTDataGet function in section 5.4.2, and the WTQueuePacketsEx function in section 5.4.5. 5.4.4 WTQueuePackets (16-bit only) Syntax DWORD WTQueuePackets(hCtx) This function returns the serial numbers of the oldest and newest packets cur¬rently in the queue. Parameter Type/Description hCtx HCTX Identifies the context whose queue is being queried. Return Value The high word of the return value contains the newest packet's serial number; the low word contains the oldest. Comments This function is non-portable and is superseded by WTQueuePacketsEx. See Also The WTQueuePacketsEx function in section 5.4.5. 5.4.5 WTQueuePacketsEx Syntax BOOL WTQueuePacketsEx(hCtx, lpOld, lpNew) This function returns the serial numbers of the oldest and newest packets cur¬rently in the queue. Parameter Type/Description hCtx HCTX Identifies the context whose queue is being queried. lpOld UINT FAR * Points to an unsigned integer to receive the oldest packet's serial number. lpNew UINT FAR * Points to an unsigned integer to receive the newest packet's serial number. Return Value The function returns non-zero if successful, zero otherwise. 5.4.6 WTQueueSizeGet Syntax int WTQueueSizeGet(hCtx) This function returns the number of packets the context's queue can hold. Parameter Type/Description hCtx HCTX Identifies the context whose queue size is being re¬turned. Return Value The return value is the number of packet the queue can hold. See Also The WTQueueSizeSet function in section 5.4.7. 5.4.7 WTQueueSizeSet Syntax BOOL WTQueueSizeSet(hCtx, nPkts) This function attempts to change the context's queue size to the value specified in nPkts. Parameter Type/Description hCtx HCTX Identifies the context whose queue size is being set. nPkts int Specifies the requested queue size. Return Value The return value is non-zero if the queue size was successfully changed. Other¬wise, it is zero. Comments If the return value is zero, the context has no queue because the function deletes the original queue before attempting to create a new one. The application must continue calling the function with a smaller queue size until the function returns a non-zero value. See Also The WTQueueSizeGet function in section 5.4.6. 5.5 Manager Handle Functions The functions described in this and subsequent sections are for use by tablet manager applications. The functions of this section create and destroy manager handles. These handles allow the interface code to limit the degree of simultaneous access to the powerful manager functions. Also, opening a manager handle lets the application receive messages about tablet interface activity. 5.5.1 WTMgrOpen Syntax HMGR WTMgrOpen(hWnd, wMsgBase) This function opens a tablet manager handle for use by tablet manager and con¬figu-ration applications. This handle is required to call the tablet management func¬tions. Parameter Type/Description hWnd HWND Identifies the window which owns the manager handle. wMsgBase UINT Specifies the message base number to use when notifying the manager window. Return Value The function returns a manager handle if successful, otherwise it returns NULL. Comments While the manager handle is open, the manager window will receive context mes-sages from all tablet contexts. Manager windows also receive information change messages. The number of manager handles available is interface implementation-dependent, and can be determined by calling the WTInfo function with category WTI_INTERFACE and index IFC_NMANAGERS. See Also The WTInfo function in section 5.1.1, the WTMgrClose function in section 5.5.2, the description of message base numbers in section 6 and the context and in¬for¬ma-tion change messages in sections 6.2 and 6.3. 5.5.2 WTMgrClose Syntax BOOL WTMgrClose(hMgr) This function closes a tablet manager handle. After this function returns, the passed manager handle is no longer valid. Parameter Type/Description hMgr HMGR Identifies the manager handle to close. Return Value The function returns non-zero if the handle was valid; otherwise, it returns zero. 5.6 Manager Context Functions These functions provide access to all open contexts and their owners, and allow changing context de¬faults. Only tablet managers are allowed to manipulate tablet contexts belonging to other applica¬tions. 5.6.1 WTMgrContextEnum Syntax BOOL WTMgrContextEnum(hMgr, lpEnumFunc, lParam) This function enumerates all tablet context handles by passing the handle of each context, in turn, to the callback function pointed to by the lpEnumFunc pa¬rameter. The enumeration terminates when the callback function returns zero. Parameter Type/Description hMgr HMGR Is the valid manager handle that identifies the caller as a manager application. lpEnumFunc WTENUMPROC Is the procedure-instance address of the call-back function. See the following "Comments" section for details. lParam LPARAM Specifies the value to be passed to the callback func-tion for the application's use. Return Value The return value specifies the outcome of the function. It is non-zero if all con¬texts have been enumerated. Otherwise, it is zero. Comments The address passed as the lpEnumFunc parameter must be created by using the MakeProcInstance function. The callback function must have attributes equivalent to WINAPI. The callback function must have the following form: Callback BOOL WINAPI EnumFunc(hCtx, lParam) HCTX hCtx; LPARAM lParam; EnumFunc is a place holder for the application-supplied function name. The actual name must be exported by including it in an EXPORTS statement in the applica-tion's module-definition file. Parameter Description hCtx Identifies the context. lParam Specifies the 32-bit argument of the WTMgrContextEnum func-tion. Return Value The function must return a non-zero value to continue enumeration, or zero to stop it. 5.6.2 WTMgrContextOwner Syntax HWND WTMgrContextOwner(hMgr, hCtx) This function returns the handle of the window that owns a tablet context. Parameter Type/Description hMgr HMGR Is the valid manager handle that identifies the caller as a manager application. hCtx HCTX Identifies the context whose owner is to be returned. Return Value The function returns the context owner's window handle if the passed arguments are valid. Otherwise, it returns NULL. Comments This function allows the tablet manager to coordinate tablet context manage¬ment with the states of the context-owning windows. 5.6.3 WTMgrDefContext Syntax HCTX WTMgrDefContext(hMgr, fSystem) This function retrieves a context handle that allows setting values for the current default digit¬izing or system context. Parameter Type/Description hMgr HMGR Is the valid manager handle that identifies the caller as a manager application. fSystem BOOL Specifies retrieval of the default system context if non-zero, or the default digitizing context if zero. Return Value The return value is the context handle for the specified default context, or NULL if the arguments were invalid. Comments The default digitizing context is the context whose attributes are returned by the WTInfo function WTI_DEFCONTEXT category. The default system context is the context whose attributes are returned by the WTInfo function WTI_DEFSYSCTX category. Editing operations on the retrieved handles will fail if the new default contexts do not meet certain requirements. The digitizing context must include at least buttons, x, and y in its packet data, and must return absolute coordinates. 1.1: Editing the current default digitizing context will also update the device-spe¬cific default context for the device listed in the lcDevice field of the default con¬text’s LOGCONTEXT structure. See Also The WTInfo function in section 5.1.1 the WTMgrDefContextEx function in section 5.6.4, and the category and index definitions in tables 7.3 through 7.9. 5.6.4 WTMgrDefContextEx (1.1) Syntax HCTX WTMgrDefContextEx(hMgr, wDevice, fSystem) This function retrieves a context handle that allows setting values for the default digit¬izing or system context for a specified device. Parameter Type/Description hMgr HMGR Is the valid manager handle that identifies the caller as a manager application. wDevice UINT Specifies the device for which a default context handle will be returned. fSystem BOOL Specifies retrieval of the default system context if non-zero, or the default digitizing context if zero. Return Value The return value is the context handle for the specified default context, or NULL if the arguments were invalid. Comments The default digitizing contexts are contexts whose attributes are returned by the WTInfo function WTI_DDCTXS multiplexed category. The default system con-texts are contexts whose attributes are returned by the WTInfo function WTI_DSCTXS multiplexed category. Editing operations on the retrieved handles will fail if the new default contexts do not meet certain requirements. The digitizing context must include at least buttons, x, and y in its packet data, and must return absolute coordinates. See Also The WTInfo function in section 5.1.1, and the category and index definitions in tables 7.3 through 7.9. 5.7 Manager Configuration Functions These functions allow manager applications to replace the default context configuration dialog and to display a configuration dialog for each hardware device. 5.7.1 WTMgrDeviceConfig Syntax UINT WTMgrDeviceConfig(hMgr, wDevice, hWnd) This function displays a custom modal tablet-hardware configuration dialog box, if one is supported. Parameter Type/Description hMgr HMGR Is the valid manager handle that identifies the caller as a manager application. wDevice UINT Identifies the device that the user will configure via the dialog box. hWnd HWND Identifies the window that will be the parent window of the dialog box. If this argument is NULL, the function will return non-zero if the dialog is supported, or zero otherwise. Return Value The return value is zero if the dialog box is not supported. Otherwise, it is one of the following non-zero values. Value Meaning WTDC_CANCEL The user canceled the dialog without making any changes. WTDC_OK The user made and confirmed changes. WTDC_RESTART The user made and confirmed changes that require a sys-tem restart in order to take effect. The calling program should query the user to determine whether to restart. Restart Windows using the function call ExitWin-dows(EW_RESTARTWINDOWS, 0);. 5.7.2 WTMgrConfigReplace (16-bit only) Syntax BOOL WTMgrConfigReplace(hMgr, fInstall, lpConfigProc) This function allows a manager application to replace the default behavior of the WTConfig function. Parameter Type/Description hMgr HMGR Is the valid manager handle that identifies the caller as a manager application. fInstall BOOL Specifies installation of a replacement function if non-zero, or removal of the current replacement if zero. lpConfigProc WTCONFIGPROC Is the procedure-instance address of the new configuration function. This argument is ignored during a re¬moval request. Return Value The function return non-zero if the installation or removal request succeeded. Oth-erwise, it returns zero. Comments This function is non-portable and is superseded by WTMgrConfigReplaceEx. See Also The WTConfig function in section 5.3.1, and for a description of the configuration callback function, see the WTMgrConfigReplaceEx function in section 5.7.3. 5.7.3 WTMgrConfigReplaceEx Syntax BOOL WTMgrConfigReplaceEx(hMgr, fInstall, lpszModule, lpszCfgProc) This function allows a manager application to replace the default behavior of the WTConfig function. Parameter Type/Description hMgr HMGR Is the valid manager handle that identifies the caller as a manager application. fInstall BOOL Specifies installation of a replacement function if non-zero, or removal of the current replacement if zero. lpszModule LPCTSTR Points to a null-terminated string that names a DLL module containing the new configuration function. This argument is ignored during a re¬moval request lpszCfgProc LPCSTR Points to a null-terminated string that names the new configuration function. This argument is ignored during a re¬moval request. Return Value The function return non-zero if the installation or removal request succeeded. Oth-erwise, it returns zero. Comments The configuration callback function must have attributes equivalent to WINAPI. Only one callback function may be installed at a time. The manager handle passed with the removal request must match the handle passed with the corre¬sponding in-stallation request. Tablet managers that install a replacement context configuration function must re-move it before exiting. Callback BOOL WINAPI ConfigProc(hWnd, hCtx) HWND hWnd; HCTX hCtx; ConfigProc is a place holder for the application-supplied function name. The actual name must be exported by including it in an EXPORTS statement in the applica-tion's module-definition file. Parameter Description hWnd Identifies the window that will be the parent window of the dialog box. hCtx Identifies the context that the user will modify via the dialog box. Return Value The function returns a non-zero value if the tablet context was changed, zero oth-erwise. Comments The configuration function and resulting dialog box should analyze the lcLocks context structure member, and only allow editing of unlocked context attributes. See Also The WTConfig function in section 5.3.1. 5.8 Manager Packet Hook Functions These functions allow manager applications to monitor, record, and play back sequences of tablet packets. 5.8.1 WTMgrPacketHook (16-bit only) Syntax WTHOOKPROC WTMgrPacketHook(hMgr, fInstall, nType, lpFunc) This function installs or removes a packet hook function. Parameter Type/Description hMgr HMGR Is the valid manager handle that identifies the caller as a manager application. fInstall BOOL Specifies installation of a hook function if non-zero, or removal of the specified hook if zero. nType int Specifies the packet hook to be installed. It can be any one of the following values: Value Meaning WTH_PLAYBACK Installs a packet playback hook. WTH_RECORD Installs a packet record hook. lpFunc WTHOOKPROC Is the procedure-instance address of the hook function to be installed. See the "Comments" section under WTMgrPacketHookEx for details. Return Value When installing a hook, the return value points to the procedure-instance ad¬dress of the previously installed hook (if any). It is NULL if there is no previous hook; it is negative one if the hook cannot be installed. The application or library that calls this func¬tion should save this return value in the library's data segment. The fourth argument of the WTPacketHookDefProc function points to the location in memory where the library saves this return value. When removing a hook, the return value is the passed lpFunc if successful, NULL otherwise. Comments This function is non-portable and is superseded by WTMgrPacketHookEx and WTMgrPacketUnhook. See Also the WTMgrPacketHookEx function in section 5.8.2, and the WTMgrPacketUn-hook function in section 5.8.3. 5.8.2 WTMgrPacketHookEx Syntax HWTHOOK WTMgrPacketHookEx(hMgr, nType, lpszModule, lpszHookProc) This function installs a packet hook function. Parameter Type/Description hMgr HMGR Is the valid manager handle that identifies the caller as a manager application. nType int Specifies the packet hook to be installed. It can be any one of the following values: Value Meaning WTH_PLAYBACK Installs a packet playback hook. WTH_RECORD Installs a packet record hook. lpszModule LPCTSTR Points to a null-terminated string that names a DLL module containing the new hook function. See the following "Comments" section for details. lpszHookProc LPCSTR Points to a null-terminated string that names the new hook function. See the following "Comments" section for details. Return Value If the function succeeds, the return value is the handle of the installed hook func-tion. Otherwise, the return value is NULL. Comments Packet hooks are a shared resource. Installing a hook affects all applications using the interface. All Wintab hook functions must be exported functions residing in a DLL module. The following section describes how to support the individual hook functions. WTH_PLAYBACK Wintab calls the WTH_PLAYBACK hook whenever a request for an event packet is made. The function is intended to be used to supply a previously recorded event packet for a compatible context. The hook function must have attributes equivalent to WINAPI. The filter function must have the following form: Hook Function LRESULT WINAPI HookFunc(nCode, wParam, lParam); int nCode; WPARAM wParam; LPARAM lParam; HookFunc is a place holder for the library-supplied function name. The actual name must be exported by including it in an EXPORTS statement in the library's mod¬ule-definition file. Parameter Description nCode Specifies whether the hook function should process the mes¬sage or call the WTMgrPacketHookDefProc (if installed by WTMgrPacketHook)or WTMgrPacketHookNext (if installed by WTMgrPacketHookEx) function. If the nCode parame¬ter is less than zero, the hook function should pass the message to the appropriate function without further process¬ing. wParam Specifies the context handle whose event is being requested. lParam Points to the packet being processed by the hook function. Comments The WTH_PLAYBACK function should copy an event packet to the buffer pointed to by the lParam pa¬rameter. The packet must have been previously recorded by us-ing the WTH_RECORD hook. It should not modify the packet. The return value should be the amount of time (in milliseconds) Wintab should wait before pro¬cess¬ing the mes¬sage. This time can be computed by calculation the difference between the time stamps of the current and previous packets. If the function returns zero, the message is processed immediately. Once it returns control to Wintab, the packet continues to be processed. If the nCode parameter is WTHC_SKIP, the hook func-tion should prepare to return the next recorded event message on its next call. The packet pointed to by lParam will have the same structure as packets re¬trieved from the context normally. Wintab will validate the following packet items to en¬sure consistency: context handle, time stamp, and serial number. The remaining fields will be valid if the context used for playback is equivalent to the context from which the events were recorded. The WTH_PLAYBACK hook will not be called to notify it of the display or re¬moval of system modal dialog boxes. It is expected that applications playing back packets will also be playing back window event messages using Windows' own hook functions. While the WTH_PLAYBACK function is in effect, Wintab ignores all hardware in-put. WTH_RECORD The interface calls the WTH_RECORD hook whenever it processes a packet from a context event queue. The hook can be used to record the packet for later playback. The hook function must have attributes equivalent to WINAPI. The hook function must have the following form: Hook Function LRESULT WINAPI HookFunc(nCode, wParam, lParam); int nCode; WPARAM wParam; LPARAM lParam; HookFunc is a place holder for the library-supplied function name. The actual name must be exported by including it in an EXPORTS statement in the library's mod¬ule-definition file. Parameter Description nCode Specifies whether the hook function should process the mes¬sage or call the WTMgrPacketHookDefProc (if installed by WTMgrPacketHook)or WTMgrPacketHookNext (if installed by WTMgrPacketHookEx) function. If the nCode parame¬ter is less than zero, the hook function should pass the message to the appropriate function without further process¬ing. wParam Specifies the context handle whose event is being processed. lParam Points to the packet being processed by the hook function. Comments The WTH_RECORD function should save a copy of the packet for later play¬back. It should not modify the packet. Once it returns control to Wintab, the message con-tinues to be processed. The filter function does not require a return value. The packet pointed to by lParam will have the same structure as packets re¬trieved from the context normally. The WTH_RECORD hook will not be called to notify it of the display or re¬moval of system modal dialog boxes. It is expected that applications recording packets will also be recording window event messages using Windows' own hook functions. 5.8.3 WTMgrPacketUnhook Syntax BOOL WTMgrPacketUnhook(hHook) This function removes a hook function installed by the WTMgrPacketHookEx function. Parameter Type/Description hHook HWTHOOK Identifies the hook function to be removed. Return Value The function returns a non-zero value if successful, zero otherwise. See Also The WTMgrPacketHookEx function in section 5.8.2, and the WTMgrPack-etHookNext function in section 5.8.5. 5.8.4 WTMgrPacketHookDefProc (16-bit only) Syntax LRESULT WTMgrPacketHookDefProc(nCode, wParam, lParam, lplpFunc) This function calls the next function in a chain of packet hook functions. A packet hook function is a function that processes packets before they are re¬trieved from a context's queue. When applications define more than one hook function by using the WTMgrPacketHook function, Wintab places func¬tions of the same type in a chain. Parameter Type/Description nCode int Specifies a code used by the hook function to determine how to process the message. wParam WPARAM Specifies the word parameter of the message that the hook function is processing. lParam LPARAM Specifies the long parameter of the message that the hook function is processing. lplpFunc WTHOOKPROC FAR * Points to a memory location that con-tains the WTHOOKPROC returned by the WTMgrPacketHook function. Wintab changes the value at this location after an appli-cation unhooks the hook using the WTMgrPacketHook function. Return Value The return value specifies a value that is directly related to the nCode parameter. Comments This function is non-portable and is superseded by the WTMgrPacketHookNext function. See Also The WTMgrPacketHookNext function in section 5.8.5. 5.8.5 WTMgrPacketHookNext Syntax LRESULT WTMgrPacketHookNext(hHook, nCode, wParam, lParam) This function passes the hook information to the next hook function in the current hook chain. Parameter Type/Description hHook HWTHOOK Identifies the current hook. nCode int Specifies the hook code passed to the current hook function. wParam WPARAM Specifies the wParam value

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值