성군.story
- [developerWorks]5월 TOP 10 기술자료 확인하세요! 2008.06.12
- 파워빌더 한글도움말 2008.06.09
- 파워스크립트의 SQL [3] 2008.06.09
- 파워스크립트의 SQL [2] 2008.06.09
- 파워스크립트의 SQL [1] 2008.06.09
- Power Builder 프로젝트 실무 - 기초에서 실무 개발자로 (CD:1) 2008.06.09
- Windows 시스템 실행파일의 구조와 원리 2008.06.09
- [파워빌더]DebugBreak 함수 2008.06.09
- SCJP 자격증 2008.06.09
- 파워빌더 API함수 2008.06.04
[developerWorks]5월 TOP 10 기술자료 확인하세요!
파워빌더 한글도움말
6.0 버전이라 누락되거나 변경된것도 있을듯 하네요..
이후 버전에 추가된 것들은 없을수도 ^^;
@@페이지 표시가 잘 안되면 파일 선택하고 속성 들어가서 차단해제 하면 잘 보입니다.
파워스크립트의 SQL [3]
Cursors
Cursors는 sql select문의 결과의 집합에 대한 포인터이다.
이것은 한번에 하나씩 여러 개의 행들을 검색하거나 작업할 수 있도록 한다. 커서는 가상변수로 생각할 수 있으며, 특수한 명령들을 이용하여 그 변수를 사용한다.
. DECLARE - 그 커서의 SELECT 문을 명시한다.
. OPEN - 그 커서의 SELECT 문을 수행한다.
. FETCH - 그 커서의 한 행을 읽는다.
. UPDATE WHERE CURRENT OF cursor - 그 읽어진 행을 수정한다.
. DELETE WHERE CURRENT OF cursor - 그 읽어진 행을 삭제한다.
. CLOSE - 커서 작업을 종료한다.
1.DECLARE
모든 변수를 선언하듯이 커서도 사용하기 전에 반드시 선언하여야 한다. 커서의 선언은 반드시 하나의 SQL SELECT 문을 포함하여야 한다. DELCLARE는 변수선언과 같이 수행문이 아니다. 그러므로 DECLARE는 그 트랜잭션객체의 SqlCode와 SqlErrText와 같은 오류 속성들의 값을 지정하지 않는다.
DECLATE cursor1 CURSOR FOR
SELECT payment, deposit
FROM checkbook
ORDER BY checkdate, checkno;
2. OPEN
커서을 선언하고 나면 그 커서를 사용하기전에 반드시 오픈하여야 한다. OPEN은 그 커서의 선언문에서 명시된 SQL SELECT 문을 수행한다. SELECT 문의 수행이 실패할 수도 있으므로 다른 수행가능한 삽입된 SQL 문과 같이 OPEN을 수행한 다음에 SqlCode을 검사하여야 한다.
OPEN cussor1;
IF sqlca.SqlCode <> 0 then.......
3. FETCH
성공적으로 커서을 오픈하면 FETCH는 하나의 행을 변수로 읽어온다. OPEN은 그 커서의 위치를 첫 번째 행의 바로전에 위치시킨다. FETCH는 묵시적으로 그 다음의 행을 읽어온다. 전형적으로 FETCH문을 루프 안에 넣고 "notfound" 오류가 발생할 때까지 반복적으로 수행한다.
DO
FETCHcusror1 INTO :decpayment, :decdeposit;
IF sqlca.SqlCode =100 THEN EXIT //더이상 남은 행이 없다.
.......
.......
.......
LOOP while True
4. UPDTE와 DELETE
한행을 읽어 온 후, 그 커서가 가리키는 그 행을 수정하거나 삭제하기 위해 WHERE CURRENT OF cursor 절과 함께 UPDATE 또는 DELETE를 사용할수 있다.
UPDATE checkbook
SET balance = :decbalance
WHERE CURRENT OF cursor1;
IF sqlca.SqlCode <> 0 then.......
물론, 단지 행을 읽기만을 원한다면 꼭 UPDATE 또는 DELETE를 사용해야 되는 의무는 없다.
5. CLOSE
커서의 작업이 끝나면 그것을 닫는다, 항상 그커서를 닫을 필요는 없다. COMMIT와 DISCONNECT가 자동적으로 그 커서를 닫아준다.
6. (예제1) : 커서를 사용하여 구조체의 행들을 읽어오기
첫째. 메뉴에서 Declare/Instance Variables를 선택 변수를 선언한다.
메뉴에서 Declare/Instance Variables를 선택하면 인스턴스 변수를 정의할수 있는 다이얼로그가 디스플레이 된다.
이곳에 단지 아래와 같은 선언문을 기술해주면된다.
DECLARE icur_store CURSOR FOR
SELECT storeid, storeaddress, storecity,
storestate,storezip, salestaxrate
FROM store;
둘째.메뉴에서 Declate/Window Structures를 선택 구조체를 정의한다.
메뉴에서 Declare/Window Structures를 선택하면 구조체를 정의할수 있는 다이얼로그가 디스플레이 된다. 이곳에 구조체의 요소들인 변수명, 변수의 타입, 그리고 타입에 따라 자리수만을 계속해서 정의해주면 된다.
일단, ws_storerow란 이름의 구조체를 정의한것으로 가정하자
셋째. (예제2)스크립트에 커서문을기술한다.
....................................................................
Integer li_rows //FETCH된열을 계산할 변수
Ws_storerow lstr_storerow
OPEN icur_store;
li_row = 0
DO
FETCH isur_store INTO
:lstr_storerow.s_storeid, :lstr_storerow.s_address,
:lstr_storerow.s_city, :lstr_storerow.s_state,
:lstr_stoterow.s_zip, :lstr_storerow.dec_salestaxrate;
IF sqlca.SqlCode = 100 THEN EXIT //더 이상의 열은 없다
li_rows ++ //하나 이상의 열을읽어 들였다.
MessageBox ("store row #" +String(li_rows), &
"Store id: -t"+lstr_storerow.s_storeid +&
"-nAddresss: -t"+lstr_storerow.s_address +&
"-nCity: -t-t"+lstr_storerow.s_city +&
"-nState: -t-t"+lstr_storerow.s_ state +&
"-nZip: -t-t"+ lstr_storerow.s_zip +&
"-nSales Tax: -t"+lstr_storerow.s_salesstaxrate +&
LOOP WHILE True
CLOSE icur_store; // 커서을 닫는다.
- 재스민의 파워빌더 싸부 수연아부지 DevTip에서 -
[출처] 파워스크립트의 SQL [3] (다우빌더) |작성자 어린왕자
파워스크립트의 SQL [2]
Null, Commit, Rollback
1. 널(Nul)값 처리
데이터베이스 테이블의 열들은 널값을 가질수있다. 널값은 공백 문자열이나 숫자 0 과는 같지않다. 종종 파워스크립트 프로그래밍을 할 때 널값에대한 특별한 처리가 필요하다.
WHERE 문에서의 예) ........... WHERE ... IS NULL;, 또는...............WHERE ... IS NOT NULL;
INSERT 문에서의 예) ........... VALUES ('9999', '8888',NULL, NULL)
UPDATE 문에서의 예) .......... SET remark = NULL WHERE.....;
1-1. 파워스크립트 산술연산에서의 널값
널값을 가지고 산술연산을 하면 그 결과 역시널값이 된다.
ex) IF IsNull(lr_a) THEN
i = 0
ELSE
i= lr_a * 0.2 / 10
END IF
만약 그 변수가 문자열 또는 다른 형의 변수라면 산술연산을 위해 비슷한 널의 처리가 필요하다.
1-2. 널 변수들과 컨트롤 속성들
SingleLineEdit 컨트롤의 Text 속성 또는 필드컨트롤의 비슷한 속성들을 널로 지정하였을 경우 예를 들어 sle_city.Text = ls_city 이 문장은 무시되고 그 컨드롤의 Text는 변경되지 않는다. 이 널값을 공백문자로 처리하려면 다음과 같은코드를 첨가 하여야 한다.
ex) IF IsNull(ls_city) THEN
sle_city.Text =""
ELSE
sle-city.Text = ls_city
END IF
1-3. SQL 산술연산의 널값들
sql문에서 산술연산이 가능하며, sql도 널값을 파워스크립트와 같은 방식으로 처리한다. 예를 들어 어떤 식의 일부의 결과가 널이라면 그식 전체의 결과가 널이 된다. 만약 널을 0과 같이 처리하려면 다음과 같이 한다.
ex) UPDATE pay
SET totalpay = IsNull(sales, 0) + IsNull(tax, 0);
sql에 있는 isnull함수는 파위스크립트의 isnull함수와 다르다, 이함수는 널이 아닌 첫번째 파라미터를 반환한다.
위의 예제에서 sales나 tax가 널값이면 다음 파라미터인 0을 반환하는 것이다.
1-4. 지시(Indicator) 변수들
변수에 널 값이 지정되었는지 알아보는 가장쉬운 방법은 위에서 기술된 바와 같이 isnull함수를 사용하는 것이다.
다른 한가지 방법은 지시변수를 사용하는 것이다.
이것은 into문에 있는 값의 다음에 위치하는 별도의 변수이다,
만약 그값이 정상이면 지시변수는 0을 반환하고 널일경우 -1, 데이터 반환 오류일경우 -2를반환한다.
ex) SELECT city, openbalance
INTO :ls_city :indvar_city,
:ls_openbal :indvar_openbal
FROM customer
WHERE custid ='7777';
IF indvar_city = -1 THEN ....... //city의 값이 널
IF indvar_openval = -1 THEN ....... //openvalance의 값이 널
2. 트랜잭션 - Commit, Rollback
하나의 트랜잭션은 성공 또는 실패의 단위로써 sql 문들의 집합이다. 이는 데이터베이스의 무결성을 보장하기 위한방법이다. 서버마다 그 구문이 조금씩 다른데, ANSI-표준 SQL에서는하나의 트랜잭션이 그 데이터베이스에 영향을 미치는 INSERT 또는 UPDATE와 같은 명령들로 시작하고, COMMIT나 ROLLBACK과 같은 명령을 사용하여 끝낸다.
ex) execute multiple SQL statement here
IF everything worked THEN
COMMIT;
ELSE
ROLLBACK;
END IF
commit는 sql 문들에 의한 데이터베이스의 변경을 영구적으로 만든다. 반면, roolback은 그 변경들을 모두 취소시킨다. 이두경우 모두 그 트랜잭션을 끝내는 것이다. 그다음에 나오는 insert나 update와 같은 sql 문이 새로운 트랜잭션을 시작한다.
파워빌더는 commit와 roolback을 삽입된 sql의 형태로 지원한다.
그래서 위와 같이 그 명령들을 스크립트에 포함하여 사용할수 있으며 필요에 따라 using절을 수반할 수도 있다.
2-1. AutoCommit
파워스크립트의 트랜잭션 객체는 autocommit라는 속성을 가지고 있는데 이 속성은 트랜잭션에 중요한 영향을 미친다.
autocommit는 불린(boolean)값을 가지며 데이터베이스에 connect하기전이나 후에 그 값을 지정할 수 있다.
sqlca.AutoCommit = False
CONNECT;
autocommit을 지원하는 데이터베이스 상품에서는
. autocommit의 값을 true로 지정하면 트랜잭션이하나도 없게 된다.
그래서 각 sql 명령은 그 즉시데이터베이스에 적용된다. 이 경우 명시적인 commit나 rollback는 아무런 의미가 없다.
. qutocommit의 값을 false로 지정하면 모든 sql명령들이 트랜잭션의 일부분이 되며,
매번작업을 완료하기 위해 commit나 rollback를 수행해야 한다.
AutoCommit는 트랜잭션 객체의 속성들중 하나이다.그러므로 다른 속성들과 같이 그 값을 지정할수있다.
sqlca.DBMS =" ......."
sqlca.Databaxe =" ......"
.......
.......
sqlca.AutoCommit = False
COMMIT;
AutoCommit 의 디폴트 값은 True이다.
한 애플리케이션에서 AutoCommit의 값은 계속해서 바꿀 수가 있다. 그래서 필요에 따라 트란잭션처리를 변경할수 있다.
예를들어 다소 간단한 모듈일 경우 는시작모듈에서 autocommit의 값을 true로,
복잡한 모듈일 경우 시작에서 autocommit의 값을 false로 지정한다.
autocommit의 값을 변경하기 위해 disconnect를 하고다시 connect할 필요는 없다.
- 재스민의 파워빌더 싸부 수연아부지 DevTip에서 -
[출처] 파워스크립트의 SQL [2] (다우빌더) |작성자 어린왕자
파워스크립트의 SQL [1]
파워빌더 애플리케이션이 데이터베이스에 접속하고 그 데이터베이스를 조작하는데 두 가지 방법이 있다.
하나는 파워스크립트 언어로 sql을 수행하는 스크립트를 작성하는 것이고, 다른 하나는 데이터원도우를 이용하는 것이다.
아래에 나오게 될 예제들은 파워스트립트 언어로 sql을 수행하여 메인프레임의 batch작업을 수행하는 것들이다.
이 스크립트는 비 대화식의 작업작업에서 부터 큰 작업까지 처리한다. 대신 데이터의 입력작업과 같이 사용자와 대화식으로 수행되는 작업에는 데이터 원도우를 사용한다.
파워스크립트에서 sql명령을 사용하는데는 두가지 방법이 있다.
.삽입된 sql - 다른 파워스크립트문과 구별없이 sql 명령들을 스크립트에 직접 첨가한다.
.동적 sql - sql 명령들을 하나의 문자열의 변수로 저장하여 데이터베이스에 보내어 수행한다.
두가지 방법중 삽입된 sql은 더 간단하고 직접적이다.
동적 sql은 더 강력하고 융통성있는 방법이며 실행시간까지 알 수 없는 파리미터들에 대한 명령들을 작성할수 있다.
데이터베이스 상품관점에서 볼때 파워스크립트는 호스트(host)언어이다.
ex1) 삽입된 UPDATA문이 있는 스크립트
Transaction trans1
trans1 = CREATE Transaction
trans1.DBMS =" ODBC"
trans1.Database =" Video Store DB"
trans1.UserId =" dba"
trans1.DBParm =" Connectstring = 'DSN = Video Store DB'"
CONNECT USING trans1;
UPDATE customer
SET address = 'dandong namgu ulsan'
WHERE firstname = 'park'
USING trans1;
DISCONNECT USING trans1;
DISTORY trans1
실제 애플리케이션에서는 정확히 이와같이 스크립트를 작성하지는 않는다.
CONNECT, UPDATE 그리고 DISCONNECT문들은 모두 그 애플리케이션의 한곳이 아니라 다른 이벤트 스크립트에 각각 놓을수 있다. 또한 trans1 대신에 sqlca라는 특별한 변수를 사용할 경우에는 이 코드의 몇줄을 삭제하여야 한다. 하지만 기본적으론 이런 골격을 갖춘다는 좋은예이다..
SQL문과 파워스크립트문의 차이점.
1. sql문은 세미콜론으로 끝나야 하지만 파워스크립트는 그렇지 않다.
2. 파워스크립트 문은 한줄이 넘어가면 "&"를 사용해야 하지만 sql은 그렇지않다.
트랜잭션 객체
바로위의 예제(1)에서 trans1이라는 이름의 변수를 많이 사용하고 있다.
대부분의 애플리케이션에서는 sqlca라는 이름의 변수를 사용하는데, 이는 파워빌더의 특별한 내장변수로 몇가지 단계를 줄여준다. 그전에 trans1은 트랜잭션 객체의 이름이다. 트랜잭션객체는 구조체와 매우 비슷한 것으로 데이터베이스 접속에 관한 정보를 저장하여 파워빌더 애플리케이션과 데이터베이스 사이의 모든 상호작용을 한다.
1-1. 트랜잭션 객체의 선언, 생성, 소멸
Transaction trans1; // 선언 - 변수 trans1을 'Transaction'자료형 변수로 선언
trans1 = CREATE Transcation // 생성 - 트랜잭션 객체를하나 생성 (메모리를 할당하고 그 값을 초기화)
DESTORY trans1 // 소멸 - 객체를 메모리에서 제거하고 그메모리를 반환.
1-2. 트랜잭션 객체의 접속 속성들
DBMS : 'ODBC' 또는 'Oracle'와 같은 데이터베이스 서버의 종류
필수
ServerName : 데이터베이스 서버의 이름
Database : 데이터베이스 이름
UserID : 사용자의 데이터베이스 ID
DBPass : 사용자의 패스워드
LlgID : 사용자의 서버 로그인 ID
LogPass : 사용자의 서버 로그인 패스워드
Lock : 트란잭션 수행하는 동안 얼마나& locking이 수행되는지 결정하는&" isolationlevel"
DBParm : 데이터베이스 서버에 의존적인 추가적인 접속 파라미터들
필수
AutoCommit : 자동적으로& commit할 것인지를 결정 (True or False)
1-3. 삽입된 SQL
위의 예제(1)에서 아래의 문장들은 삽입된 SQL이다.
CONNECT USING trans1; //데이터베이스에 접속, 이것은데이터베이스 페인트에서 File/Connect 메뉴를 선택하는 것과 같다.
UPDATE customer
SET address = 'dandong namguulsan'
WHERE firstname = 'park'
USING trans1;
DISCONNECT USING trans1; //데이터베이스의 접속을 단절.
1-4. 삽입된 SQL의 USING 절
한번의 트랜잭선 객체 변수를 선언하여 초기화하면 그것을 각 삽입된 SQL문의 마지막에 USING 절로 마무리짓는다.
USING절은 그 SQL 문을 올바른 데이터베이스에 보내기 위해 필요한 것이다.
애플리케이션에서 여러개의 데이터베이스에 접속하면 그 각각에 대해 별도의 트랜잭션객체를 선언하여야 한다.
그리고 USING 절을 이용하여 해당 데이터베이스를 올바르게 인식시킨다.
디폴트는 USING sqlca이며 디폴트로 지정하였을 경우 따로 지정을 인식시킬 필요는 없다.
실제의 예제
실제 프로그래밍에서는 아래의 몇가지 있다.
1. 오류 처리루틴을 첨가해야 한다.
2. 트랜잭션 객체를 sqlca를 사용하는것이 편리하다.
3. 모든 스크립트에서 매번 트랜잭션을 접속하고 접속을 끊는것보다 애플리케이션이 시작될때
한번 접속한후 계속 접속상태로 두는것이 더좋다.
4. 위의 예제에서는 그 트랜잭션 객체의 속성들에 대한 값들을 일일이 코딩하였다.
그러나 그 값들을 PB.INI나 다른 .INI파일로부터 가져오도록 하면 그 애플리케이션을 보다 융통성있게 관리할수 있다.
1-1. 오류처리
오류반환속성 : 내용
반환값
자료형
SqlCode : 성공 또는 실패여부
성공 : 0, 실패 : -1, 처리없음 : 100
long
SqlRorw : 처리된 행들의 갯수
long
SqlDBCode : 데이터베이스가 명시하는 오류코드
long
SqlErrText : 오류발생시 오류메세지
string
SqlReturnData : 유용한 정보메세지
string
ex2) 오류처리의 예
UPDATE customer
SET address = 'dandong namgu ulsan'
WHERE firstname = 'park'
USING trans1;
IF trans1.sqlcode <> 0 THEN
MessageBox("Error on Update",&
"Error Code:" + String(trans1.SqlDbCode) +&
" -nError Message =" + trans1.sqlErrText, &
StopSign!)
RETURN
END IF
위에 예제는 sql실행시 에러처리의 예이며 connect와 disconect 다음의 문장에도 에러처리를 첨가하여야 한다.
1-2. Sqlca의 사용 SQL통신영역(Communications Area)
파워빌더는 자동적으로 하나의 전역 트랜잭션객체 변수를 선언하고 생성한다.
그것이 salca이다. sqlca를 사용하였을 경우의 이점은
1. sqlca를 선언, 생성, 소멸할 필요가 없다. 이작업들은 파워빌더가 자동적으로 해준다.
2. 모든 sql 문 뒤에 using 절을 사용할 필요가 없다, 파워빌더가 디폴트로 USING sqlca를 첨가한다.
ex3) sqlca를 사용한 스크립트
sqlca.DBMS =" ODBC"
sqlca.Database =" Video Store DB"
sqlca.UserId =" dba"
sqlca.DBParm =" Connectstring = 'DSN = Video Store DB'"
CONNECT USING trans1;
UPDATE customer
SET address = 'dandong namgu ulsan'
WHERE firstname = 'park'
DISCONNECT;
1-3. 전역 접속(Global Connection)
보통 애플리케이션이 수행되는 동안에는 데이터베이스에 계속 연결된 상태로 있기를 원한다. 그래서 CONNECT 의 적절한 사용위치는 애플리케이션의 'open'이벤트 스크립트에 기술하며, DISCONNECT 의 적절한 사용위치는 애플리케이션의'close'이벤트 스크립트에 기술한다. 이렇게 하면 다른 스크립트에서 더이상 CONNECT, DISCONNECT를 기술할 필요가 없으며 대부분의 서버에서 CONNECT는 매우늦은 연산이므로 가능한 적게 사용하는 것이 좋다.
1-4. INI 파일로부터 접속 파라미터 읽기
스크립트에서 트랜잭션 속성들의 값을 직접코딩하는 것은 대부분의 실-세계애플리케이션에서 융통성이 없어지므로 그 속성의 일부 또는전부를 .INI 파일에서 읽도록 해야 한다. 각 사용자가 PB.INI파일을 가지고 있다고 확신한다면 그 파일을 사용할수 있다. (또는 그 애플리케이션만의 .INI 파일을 별도로 가질수 있다.)
다음 예제는 PB.INI 파일에서 'Video Store'라는명칭의 데이터베이스의 접속 파라미터를 정의하는 예이다.
ex4) PB.INI의 PROFILE 섹션
[Profile Video Stoe DB]
DBMS = ODBC
Database = Video Store DB
UserID =
DatabasePassword =
LogPassword =
ServerName =
LogID =
DbParm = Connectring = 'DSN = Video Store DB; UID = dba'
Autocommit = 0
Prompt = 0
다음 예제는 PB.INI로 부터 그파라미터를 읽어와서 sqlca의 속성들에 저장하는 방법을 보여준다.
파워빌더는 .INI 파일의 파라미터를 읽기위해 ProfileString 함수를 제공한다.
ex5) PB.INI로부터 트랜잭션 속성읽기
String ls_inifile, ls_section, ls_dbms
ls_inifile =" PB.INI"
ls_section =" PROFILE Video Store DB"
ls_dbms = ProfileString(ls_infile, ls_section," DBMS","" )
IF ls_dbms ="" THEN
MessageBox("Error on Connect to Video Store DB", &
"Unable to read DBMS vender from the"+&
ls_section +" section of INI file" +&
ls_inifile, &
stopsign!)
RETURN
END IF
sqlca.Database = ProfileString(ls_inifile. ls_section," Database","" )
sqlca.ServerName = ProfileString(ls_inifile. ls_section," ServerName","" )
sqlca.UserID = ProfileString(ls_inifile. ls_section," UserID","" )
sqlca.DBPass = ProfileString(ls_inifile. ls_section," DatabasePassword","" )
sqlca.LogId = ProfileString(ls_inifile. ls_section," LogId","" )
sqlca.Lock = ProfileString(ls_inifile. ls_section," Lock","" )
sqlca.DBParm = ProfileString(ls_inifile. ls_section," DBParm","" )
sqlca.DBMS = ls_dbms
CONNECT;
- 재스민의 파워빌더 싸부 수연아부지 DevTip에서 -
[출처] 파워스크립트의 SQL [1] (다우빌더) |작성자 어린왕자
Power Builder 프로젝트 실무 - 기초에서 실무 개발자로 (CD:1)
![]() | |
본서는 파워빌더를 성격으로 접근하면서, 실제로 프로그램을 개발하는 방법과 감각을 얻는데 도움이 되도록 초점을 맞추어져 있습니다. 인사관리 시스템이라는 프로그램을 중심으로 프로젝트의 시작부터 끝까지의 과정을 주로 개발에 초점을 두어 설명합니다. | |
| |
![]() | |
Project 출발 - 파워빌더와 프로젝트 - 본 책을 공부하기 위한 환경 설정 Project 준비과정 - 프로젝트 범위 설정 - 업무정형화 / 자료 흐름도 Project 진행 I - 디자인 - 프로젝트의 DB설계, Table설계, 업무설계 - 화면 디자인 Project 진행 II - 개발 (기본 디자인) - 공통 모듈 - User Object, Function, Window Project 진행 III - 개발 (인사관리 시스템) - 신상관리, 조직관리, 통계, 보안관리 - 프로그램 개발 Project 마무리 및 유지보수 - 실행 모듈 만들기 - 유지보수 Tip & Technique - [인사관리 시스템] 내용 외에 Tip - Technique 예제 //회사에서 파워빌더를 하게 되서 구입하게 된책... |
Windows 시스템 실행파일의 구조와 원리
![]() |
Windows OS구조와 원리를 학습하는 또 다른 방법 - 프로그램의 실행 원리를 아는 것이 시스템(OS)을 이해하는 것이다 이 책이 다루는 정확한 영역은 우리가 보통 애플리케이션이라고 부르는 EXE 파일과 EXE 실행시에 함께 로드되는 동적 라이브러리인 DLL의 구조와 포맷 분야이다. 각 구조에 대한 상세한 설명뿐만 아니라 예제 덤프를 통해 생생하게 그 구조를 파악하게끔 구성하고 있다. 디버깅 툴 제작이나 탐침 혹은 백신 프로그램, API 후킹 프로그램과 같은 고급 영역에 밀접하게 관계되어 있지만, 실제로는 Win32 시스템 영역 즉 OS 영역을 이해하는 데 더할 나위 없이 좋은 학습 영역이기도 하다. 윈도우즈 프로그래밍을 다소 깊게 하다 보면 자연스레 부족한 부분을 느낄 것이고 이 책이 그러한 부분을 상당 부분 해소시켜 줄 것이다. 주요 내용 > 모든 장에서 예제 덤프를 통한 생생한 구조 분석 > 실행 파일 분석을 통한 VMM(Virtual Memory Manager)과 실행파일의 관계 > DLL 익스포트와 임포트의 과정 및 포맷 분석을 통한 실행 파일 내에서의 DLL 정보 추출 그리고 개발자가 놓치고 있던 DLL 관련 사항 정리 > Windows 2000부터 지원되는 새로운 DLL 로딩 방식인 DLL 지연 로딩과 그 과정에 대한 철저한 분석 > 실행파일 내부에 존재하는 리소스와 리소스 타입별(아이콘, 메뉴 등등) 포맷 상세 분석 및 실행 파일에서 필요한 리소스를 뽑아낼 수 있는 방법 연구 > DLL 재배치의 의미와 그 과정 및 재배치 섹션 구조에 대한 상세 분석 |
[파워빌더]DebugBreak 함수
DebugBreak PowerScript function
[설명]
실행을 보류하고 Debug 윈도우를 오픈한다.
[문법]
DebugBreak ( )
[Return 값]
없음
[용법]
응용프로그램 실행을 보류하고 테스트하려는 위치에 DebugBreak 함수를 삽입한다.
디버깅을 가능하게 하고 개발환경에서 응용프로그램을 실행한다.
PowerBuilder가 DebugBreak 함수를 만나면
Debug 윈도우가 오픈되고 현재 내용을 나타낸다.
[예제]
다음 문장은 변수의 NULL 값 여부를 테스트하고 NULL 값이면 Debug 윈도우를 오픈한다:
IF IsNull(auo_ext) THEN DebugBreak() [출처] [파워빌더]DebugBreak 함수|작성자 연쓰
SCJP 자격증
파워빌더 API함수
Arc( )
주어진 좌표를 이용하여 아크를 그린다.
Global External Function:
FUNCTION boolean Arc(ulong hwnd, long r1, long r2, long r3, long r4, long a1, long a2, long a3, long a4) LIBRARY "Gdi32.dll"
Script:
Boolean rtn
ulong l_handle, l_device
long lv[8]
l_handle = handle(w_main) // 'w_main' is the name of the sample window.
l_device = GetDC(l_handle)
lv[ ] = {10,40,300,220,0,0,180,0}
rtn = Arc(l_device, lv[1], lv[2], lv[3], lv[4], lv[5], lv[6], lv[7], lv[8])
Beep( )
삑 소리가 나게 한다.
Global External Function:
FUNCTION boolean Beep(long freq,long dur) LIBRARY "Kernel32.dll"
Script:
Boolean rtn
Long ll_freq, ll_dur
ll_freq = 500
ll_dur = 20
rtn = Beep(ll_freq, ll_dur)
BringWindowToTop( )
타겟 윈도우에게 가장 위쪽으로 나오도록 메시지를 보낸다. 파워빌더의 오브젝트명.bringtotop = true과 동일하다.
Global External Function:
FUNCTION boolean BringWindowToTop(ulong w_handle) LIBRARY "User32.dll"
Script:
Boolean rtn
ulong l_handle
l_handle = handle(w_win2)
rtn = BringWindowToTop(l_handle)
Chord( )
주어진 좌표에 기반을 둔 현(사각형, 타원(?))을 그린다.
Global External Function:
FUNCTION boolean Chord(ulong hwnd,long x1,long y1,long x2,long y2,long r1, long r2, long r3, long r4) LIBRARY "Gdi32.dll"
Script:
boolean rtn
ulong l_handle, l_device
long lv[8]
l_handle = handle(w_main)
l_device = GetDC(l_handle)
// This can be done in one line: i.e. l_device = GetDC(handle(w_main))
lv[ ] = {5,5,200,200,0,0,200,300}
rtn = Chord(l_device, lv[1], lv[2], lv[3], lv[4], lv[5], lv[6], lv[7], lv[8])
CloseHandle( )
이 함수는 열려있는 오브젝트의 핸들을 release한다.
Global External Function:
FUNCTION boolean CloseHandle(ulong w_handle) LIBRARY "Kernel32.dll"
Script:
boolean rtn
ulong l_handle
l_handle = FindWindowA(0,"<window or object name>") // Usually you would already have the handle.
rtn = CloseHandle(l_handle)
CloseWindow( )
타켓 윈도우를 미니마이즈시킨다.(닫지 않는다)
Global External Function:
FUNCTION boolean CloseWindow(ulong w_handle) LIBRARY "User32.dll"
Script:
boolean rtn
ulong l_handle
l_handle = FindWindowA(0,"File manager") // Be sure to use the exact title of the window you are targeting.
rtn = CloseWindow(l_handle)
CopyFileA( )
이 함수는 파일을 복사한다.
Global External Function:
FUNCTION boolean CopyFileA(ref string cfrom, ref string cto, boolean flag) LIBRARY "Kernel32.dll"
Script:
string l_from, l_to
boolean l_flag, rtn
l_flag = false
l_from = "c:\pwrs\pb5i32\ex\code\beach.bmp"
l_to = "c:\test.bmp"
rtn = CopyFileA(l_from, l_to, l_flag)
MessageBox("CopyFile", string(rtn))
CreateDirectoryA( )
새로운 디렉토리 폴더를 생성한다.
Global External Function:
FUNCTION boolean CreateDirectoryA(ref string pathname, int sa) LIBRARY "Kernel32.dll"
Script:
boolean rtn
string l_dir
l_dir = "API Demo"
rtn = CreateDirectoryA(l_dir, 0)
If rtn then
MessageBox("New Directory Created", "API Demo directory is located under pwrs.")
else
MessageBox("CreateDirectory", "Failed")
end if
DeleteFileA( )
지정된 파일을 삭제한다.
Global External Function:
FUNCTION boolean DeleteFileA(ref string filename) LIBRARY "Kernel32.dll"
Script:
string l_file
boolean rtn
l_file = string(sle_to.text)
rtn = DeleteFileA(l_file)
MessageBox("DeleteFile", string(rtn))
DeleteMenu( )
이 함수는 지정된 메뉴아이템을 삭제하는데 사용된다.
Global External Function:
FUNCTION boolean DeleteMenu(ulong mhand, uint upos, uint flag) LIBRARY "user32.dll"
Script:
ulong m_handle
boolean rtn
m_handle = GetSystemMenu(handle(w_main), false) // Need to get the handle of the system menu first.
rtn = DeleteMenu(m_handle, 1, 0) // The second argument, the '1', refers to the position in the menu.
Messagebox("Return Code", string(m_handle))
Messagebox("Return Code", string(rtn))
DestroyWindow( )
이 함수는 타겟윈도우에게 Destory메시지를 보낸다. 파워빌더의 Close("윈도우명")과 동일하다.
Global External Function:
FUNCTION boolean DestroyWindow(ulong w_handle) LIBRARY "USER32.DLL"
Script:
boolean rtn
ulong l_handle
open(w_win2) // Open a test window
l_handle = handle(w_win2)
rtn = DestroyWindow(l_handle)
DllRegisterServer( )
이 함수는 OCX가 자동적으로 등록되도록 해 준다. 이 함수는 constructor이벤트에서 파워빌더 에플리케인션이 이 동작되고 있는 동안에 동적으로 OCX를 등록할때 사용된다.
Global External Function:
FUNCTION long DllRegisterServer() LIBRARY "c:\windows\ocxname.ocx"
Script:
Long ll_rtn
ll_rtn = DllRegisterServer()
//Note: A return code of zero most likely means the OCX is already registered.
Ellipse( )
이 함수는 원에 기반을 둔 타원을 그린다.
Global External Function:
FUNCTION boolean Ellipse(ulong hwnd,long x1,long y1,long x2,long y2) LIBRARY "Gdi32.dll"
Script:
Boolean rtn
ulong l_handle, l_device
long lv[4]
l_handle = handle(w_main)
l_device = GetDC(l_handle)
lv[ ] = {5,5,300,300}
rtn = Ellipse(l_device, lv[1], lv[2], lv[3], lv[4])
ExitWindowsEx( )
이 함수는 윈도우 O/S에게 윈도우가 종료되어야 함을 알려 윈도우 O/S가 종료되게 한다.
Global External Function:
FUNCTION boolean ExitWindowsEx(uint dwReserved, uint uReserved) LIBRARY "User32.dll"
Script:
boolean rtn
rtn = ExitWindowsEx(0,0) // Zero's tell it to shut down immediately.
FatalExit( )
이 함수는 실행중인 에플리케이션을 강제로 종료시킵니다. 디버깅의 용도로는 사용하되 다른 용도로는 사용하지 않는 것이 좋다.
Global External Function:
SUBROUTINE FatalExit(int exitcode) LIBRARY "Kernel32.dll"
Script:
int rtn
rtn = MessageBox("This API call is suppose to produce a GPF!","Are You Sure?", Exclamation!, YesNo!,2)
If rtn = 1 Then
MessageBox("Final Notice!","You will have to reboot after this API call!")
FatalExit(1)
End If
FindWindowA( )
이 함수는 이름으로 호출된 윈도우의 핸들을 리턴합니다. 파워빌더 윈도우즈에서만 사용가능합니다. 파워빌더의 Handle( )과 유사합니다.
Global External Function:
FUNCTION ulong FindWindowA(ulong classname,string windowname) LIBRARY "User32.dll"
Script:
ulong l_handle
l_handle = FindWindowA(0,"<window name>") // i.e. "File Manager" or "Numbers.txt - NotePad"
FreeLibrary( )
이 함수는 활성 메모리에서 dll을 release시킵니다. 이 함수는 LoadLibraryA( )와 결합되어 사용됩니다.
Global External Function:
SUBROUTINE FreeLibrary(ulong libhandle) LIBRARY "Kernel32.dll"
Script:
ulong modhandle // This would usually be an instance variable
modhandle = LoadLibraryA("<32 bit dll filename>") // This would usually be done in another event.
FreeLibrary(modhandle)
GetBkColor( )
이 함수는 윈도우의 백그라운트 칼라를 reference number에 의해 return합니다. 파워빌더의 다음 스크립트와 유사합니다. ulong l_color
l_color = w_main.BackColor
Global External Function:
FUNCTION ulong GetBkColor (ulong hwnd) LIBRARY "Gdi32.dll"
Script:
ulong l_handle, l_device, l_color
l_handle = handle(w_main)
l_device = GetDC(l_handle)
l_color = GetBkColor(l_device)
GetCapture( )
마우스에 의해 캡쳐된 윈도우의 핸들을 리턴합니다. 이때 윈도우는 마우스 커서가 어디에 있는가는 상관하지 않습니다.
Global External Function:
FUNCTION ulong GetCapture( ) LIBRARY "User32.dll"
Script:
ulong l_handle
l_handle = GetCapture( )
GetComputerNameA( )
이 함수는 컴퓨터의 이름을 참조의 방법으로 return합니다. 충분한 버퍼를 확보해야 합니다.
Global External Function:
FUNCTION boolean GetComputerNameA(ref string cname,ref long nbuf) LIBRARY "Kernel32.dll"
Script:
string ls_compname
long ll_buf
ll_buf = 25
ls_compname = space(ll_buf)
GetComputerNameA(ls_compname, ll_buf)
MessageBox("Computer name is:", ls_compname)
GetClassNameA( )
이 함수는 어떤 오브젝트나 윈도우의 핸들을 이용하여 클래스명을 리턴합니다. 충분한 버퍼를 확보해야 합니다.
Global External Function:
Function long GetClassNameA(ulong hwnd, ref string cname, int buf) Library "User32.dll"
Script:
string l_class
long rtn
ulong l_handle
l_handle = handle(w_main)
l_class = space(50)
rtn = GetClassNameA(l_handle,l_class,50)
Messagebox("Classname", l_class)
GetCurrentDirectoryA( )
이 함수는 현재 작업디렉토리를 return합니다. 디렉토리 명이 다 들어갈만한 충분한 크기의 버퍼를 확보해야 합니다.
Global External Function:
FUNCTION ulong GetCurrentDirectoryA(ulong BufferLen, ref string currentdir) LIBRARY "Kernel32.dll"
Script:
string ls_curdir
ulong l_buf
l_buf = 100
ls_curdir = space(l_buf)
GetCurrentDirectoryA(l_buf, ls_curdir)
MessageBox("Current Directory:", ls_curdir)
GetCurrentThread( )
이 함수는 현재 thread의 handle을 return합니다.
Global External Function:
FUNCTION ulong GetCurrentThread() LIBRARY "Kernel32.dll"
Script:
ulong rtn
rtn = GetCurrentThread()
MessageBox("Current Thread Handle", string(rtn))
GetCursor( )
이 함수는 커서의 핸들을 return합니다.
Global External Function:
FUNCTION ulong GetCursor( ) LIBRARY "User32.dll"
Script:
ulong l_cursor
l_cursor = GetCursor( )
GetCursorPos( ) & SetCursorPos( )
GetCursorPos()는 structure Mousepos를 이용해서 마우스의 x, y좌표를 return합니다. SetCursorPos()는 주어진 좌표로 마우스 커서를 이동시킵니다.
Global External Function:
FUNCTION boolean GetCursorPos(ref mousepos mousepos2) LIBRARY "User32.dll"
FUNCTION boolean SetCursorPos(int cx, int cy) LIBRARY "User32.dll"
Structure: (Mousepos)
long xpos, long ypos
Script:
mousepos mouseloc
GetCursorPos(mouseloc)
Messagebox("Cursor Position", "X = " + string(mouseloc.xpos) + " Y = " + string(mouseloc.ypos))
SetCursorPos(300,350)
Messagebox("Cursor Position", "X = " + string(mouseloc.xpos) + " Y = " + string(mouseloc.ypos))
GetDC( )
이 함수는 주어진 윈도우 핸들의 device context를 return합니다. device context는 어떤 그래픽함수를 호출하고자 할 경우에 필요합니다. 파워빌더에는 비숫한 함수가 없습니다.
Global External Function:
Function ulong GetDC(ulong hwnd) library "user32.dll"
Script:
ulong l_handle, l_device
l_handle = handle(w_main)
l_device = GetDC(l_handle)
MessageBox("Handle", string(l_device))
GetKeyboardState( ) & SetKeyboardState( )
첫번째 함수는 키보드의 모든 키의 상태를 256개의 ASCII배열에 의해서 return합니다. 두번째 함수는 주어진 배열의 상태에 따라서 키보드 상태를 set합니다. 여기에서 0은 키보드가 눌러지지 않는 것을 의미하고 그렇지 않은 값은 키보드가 눌러진 것을 의미합니다.
Global External Function:
FUNCTION boolean GetKeyboardState(ref integer kbarray[256]) LIBRARY "USER32.DLL"
FUNCTION boolean SetKeyboardState(ref integer kbarray[256]) LIBRARY "USER32.DLL"
Script:
//GetKeyboardState( )
boolean rtn
integer ipkey[256]
rtn = GetKeyboardState(ref ipkey)
//SetKeyboardState( )
rtn = SetKeyboardState(ref ipkey)
if rtn = false then
Messagebox("Failed","Something went wrong when loading into array")
else
Messagebox("Successful","Keyboard state is loaded back into buffer")
end if
GetKeyState( )
이 함수는 현재 키보드의 특정한 키의 상태를 ASCII값으로 참조하여 return합니다.
Global External Function:
Function int GetKeyState(integer VirtualKeycode) Library "User32.dll"
Script:
int rtn
rtn = GetKeyState(65) // 65 = A
if rtn = 0 then
MessageBox("Key State","Letter 'A' not pressed!")
else
MessageBox("Key State","Letter 'A' is pressed!")
end if
GetModuleHandleA( )
이 함수는 활성 메모리의 모듈이나 dll의 핸들을 return합니다.
Global External Function:
Function long GetModuleHandleA(string modname) Library "Kernel32.dll"
Script:
ulong rtn
rtn = GetModuleHandleA("User32.dll")
MessageBox("Return Code", string(rtn))
GetParent( )
이 함수는 child handle을 검색하여 parent handle을 return합니다. 파워빌더의 'GetParent()'가 이 함수와 동일합니다.
Global External Function:
FUNCTION ulong GetParent(ulong hwnd) LIBRARY "User32.dll"
Script:
ulong l_handle, rtn
l_handle = handle(cb_getparent) // Command Button name
rtn = GetParent(l_handle)
Messagebox("GetParent", "Parent handle = " + string(rtn) + " / Child handle = " + string(l_handle))
GetPixel( ) & SetPixel( )
첫번째 함수는 특정한 픽셀의 색을 알려주며 두번째 함수는 특정한 좌표의 색을 변경합니다.
Global External Function:
FUNCTION ulong GetPixel(ulong hwnd, long xpos, long ypos) LIBRARY "Gdi32.dll"
FUNCTION ulong SetPixel(ulong hwnd, long xpos, long ypos, ulong pcol) LIBRARY "Gdi32.dll"
Script:
long lx, ly
ulong rtn
ulong l_handle, l_device
lx = 100
ly = 100
l_handle = handle(w_main)
l_device = GetDC(l_handle)
rtn = GetPixel(l_device, 100, 100)
MessageBox("Position " + string(lx) + "," + string(ly),"Color = " + string(rtn))
SetPixel(l_device, lx, ly, 0) // This call will set the pixel at lx, ly to black.
GetSystemMetrics( )
이 함수는 현재 화면의 해상도 픽셀단위를 이용해서 알려줍니다. 이 함수는 아주 민감하여 정확히 선언을 해야 하며 "GetSystemMetrics"라고 선언해야 하는데 "getsystemmetrics"로 선언하면 절대 안됩니다.
Global External Function:
FUNCTION int GetSystemMetrics(int indexnum) LIBRARY "user32.dll"
Script:
int l_xx, l_yy
l_xx = GetSystemMetrics(0)
l_yy = GetSystemMetrics(1)
Messagebox("Screen Resolution", string(l_xx) + " , " + string(l_yy))
GetSystemMenu( )
이 함수는 에플리케인션이 복사 또는 수정을 위해 시스템이나 윈도우즈의 메뉴를 사용할 수 있게 합니다.
Global External Function:
FUNCTION boolean GetSystemMenu(ulong mhandle, boolean flag) LIBRARY "user32.dll"
Script:
boolean flag
ulong l_handle, m_handle
l_handle = handle(w_main)
flag = false
m_handle = GetSystemMenu(l_handle, flag)
Messagebox("Return Code", string(m_handle))
GetSystemTime( )
이 함수는 structure SystemTime을 이용하여 시스템 타임을 return합니다.
Global External Function:
SUBROUTINE GetSystemTime(ref systemtime systimeptr) Library "Kernel32.dll"
Structure: (SystemTime)
uint year, uint month, uint dayofweek, uint day, uint hour, uint minute, uint second, uint millisecond
Script:
systemtime s_systime
string l_day, l_date, l_time
GetSystemTime(s_systime)
l_date = string(s_systime.month) +"/"+ string(s_systime.day) &
+"/"+ string(s_systime.year)
l_time = string(s_systime.hour) +":"+ string(s_systime.minute) &
+":"+ string(s_systime.second) +":"+ string(s_systime.millisecond)
CHOOSE CASE s_systime.dayofweek
CASE 1
l_day = "Sunday"
CASE 2
l_day = "Monday"
CASE 3
l_day = "Tuesday"
CASE 4
l_day = "Wednesday"
CASE 5
l_day = "Thursday"
CASE 6
l_day = "Friday"
CASE 7
l_day = "Saturday"
END CHOOSE
Messagebox("System Time:",l_date + " " + l_day + " " + l_time)
GetThreadPriority( )
이 함수는 주어진 thread의 우선 순위를 return합니다.
Global External Function:
FUNCTION int GetThreadPriority(ulong hthread) LIBRARY "Kernel32.dll"
Script:
ulong l_handle
integer rtn
l_handle = GetCurrentThread()
rtn = GetThreadPriority(l_handle)
MessageBox("Current Thread Priority", string(rtn))
GetUserNameA( )
이 함수는 현재 유저의 로그온 네임을 return합니다. (유저명을 저장할 수 있을 만큼의 충분한 버퍼를 확보해야 합니다.)
Global External Function:
FUNCTION boolean GetUserNameA(ref string uname, ref ulong slength) LIBRARY "ADVAPI32.DLL"
Script:
string ls_username
string ls_var
ulong lu_val
boolean rtn
lu_val = 255
ls_username = Space( 255 )
rtn = GetUserNameA(ls_username, lu_val)
Messagebox("GetUserNameA", "Username = " + string(ls_username))
GetWindowsDirectoryA( )
이 함수는 윈도우즈 디렉토리를 return하며 디렉토리를 얻기 위해 디렉토리가 저장될 만한 길이의 충분한 메모리를 확보해야 합니다.
Global External Function:
FUNCTION ulong GetWindowsDirectoryA(ref string wdir, ulong buf) LIBRARY "kernel32.dll"
Script:
ulong l_buf
string windir
l_buf = 144
windir = space(144)
GetWindowsDirectoryA(windir, l_buf)
MessageBox("Current Directory", windir)
GlobalMemoryStatus( )
이 함수는 structure Memory를 이용하여 현재 메모리의 모든 정보를 리턴합니다.
Global External Function:
SUBROUTINE GlobalMemoryStatus(ref memory mem2) LIBRARY "Kernel32.dll"
Structure:(Memory)
ulong m_length, ulong m_loaded, ulong m_totalphys, ulong m_availphys, &
ulong m_totalpagefile, ulong m_availpagefile, ulong m_totalvirtual, &
ulong m_availvirtual
Script:
memory sysmem
GlobalMemoryStatus(sysmem)
Messagebox("Memory Length", string(sysmem.m_length))
Messagebox("Memory Loaded", string(sysmem.m_loaded))
Messagebox("Total Physical Memory", string(sysmem.m_totalphys))
Messagebox("Total Available Memory", string(sysmem.m_availphys))
Messagebox("Total Page Size", string(sysmem.m_totalpagefile))
Messagebox("Available Page Size", string(sysmem.m_availpagefile))
Messagebox("Total Virtual Memory", string(sysmem.m_totalvirtual))
Messagebox("Available Virtual Memory", string(sysmem.m_availvirtual))
LoadLibraryA( )
이 함수는 dll을 (활성)메모리에 로드합니다. 32비트에서만 사용할 수 있습니다.
Global External Function:
FUNCTION ulong LoadLibraryA(string modname) LIBRARY "Kernel32.dll"
Script:
ulong modhandle
modhandle = LoadLibraryA("c:\windows\mydll.dll") // Pathing isn't necessary if dll is in dos search path.
If modhandle > 0 Then
MessageBox("Return Code", "Load Successful -> handle = " + string(modhandle))
else
MessageBox("Result","Unable to load module")
end if
MciSendStringA( )
이 함수는 AVI파일을 PLAY하며 사용법이 좀 복잡합니다. 파워빌더에는 비슷한 함수가 없습니다.
Global External Function:
FUNCTION long MciSendStringA(string cmd, REF string rtn, long size, long wnd) LIBRARY "winmm.dll"
Script:
string s_errortext
string filename
filename = "c:\pwrs\pb5i32\ex\code\pbspin.avi"
MciSendStringa ("open "+Filename+" type AVIVideo alias test wait",s_errortext, 0,0)
MciSendStringa ("Window test handle " + string(handle(w_main)) + " wait",s_errortext, 0, 0)
MciSendStringa ("Put test destination wait",s_errortext, 0, 0)
MciSendStringa ("Play test wait", s_errortext, 0, 0)
MciSendStringa ("Close test", s_errortext, 0, 0)
MessageBoxA( )
이 함수는 메시지 박스를 출력합니다. 파워빌더의 MessageBox()와 유사합니다.
Global External Function:
FUNCTION long MessageBoxA(ulong hwnd, ref string text, ref string title, ulong style) LIBRARY "User32.dll"
Script:
long rtn
ulong handle1, style1
string text1
string title1
handle1 = handle(parent)
text1 = "This is an API Messagebox"
title1 = "API MessageBox"
style1 = 0
rtn = MessageBoxA(handle1,text1,title1,style1)
Mouse_Event( )
이 함수는 마우스 포인터를 이동시키거나 마우스 버튼의 클릭이벤트를 발생시키거나 기타 유저가 마우스를 이용하여 할 수 있는 일을 합니다. 아래의 예제는 마우스를 왼쪽으로 80픽셀, 위로 50픽셀이동시킵니다. structure mousepos는 마우스의 이동전의 좌표입니다.
Global External Function:
SUBROUTINE Mouse_Event(ulong dwflag,ulong dx,ulong dy,ulong cbutton,ulong dwextra) LIBRARY "User32.dll"
Structure: (Mousepos)
long xpos, long ypos
Script:
int l_loop, lx, ly, lflag
mousepos mouseloc
lx = mouseloc.xpos
ly = mouseloc.ypos
lflag = 1 //1 = do nothing, 7 = L-button clicked, 25 = R-button clicked
mouse_event(lflag,-80,-50,0,0)
MoveToEx( ) & LineTo( )
MoveToEx()는 주어진 좌표로 커서를 이동시키며, LineTo()는 현재 좌표에서 주어진 좌표까지 라인을 그립니다.
Global External Function:
FUNCTION boolean MoveToEx(ulong hwnd,long wx, long wy,ref prepos prepos2) LIBRARY "Gdi32.dll"
FUNCTION boolean LineTo(ulong hwnd,long wx, long wy) LIBRARY "Gdi32.dll"
Structure: (Prepos)
long xpos, long ypos
Script:
ulong l_handle, l_device
prepos previouspos
l_handle = handle(w_main)
l_device = GetDC(l_handle)
MoveToEx(l_device,100,100,previouspos)
LineTo(l_device,200,200)
MoveWindow( )
이 함수는 주어진 값에 따라 윈도우의 위치 및 크기를 변경합니다.
Global External Function:
FUNCTION boolean MoveWindow(ulong whand,int wx,int wy,int ww,int wh,boolean wflag) LIBRARY "user32.dll"
Script:
boolean rtn
ulong l_handle, l_device
l_handle = handle(w_main)
rtn = MoveWindow(l_handle,10,10,100,100,true)
MessageBox("Return Code",string(rtn))
Pie( )
이 함수는 주어진 좌표를 이용하여 파이챠트에 기반을 둔 반원을 그립니다.
Global External Function:
FUNCTION boolean Pie(ulong hwnd,long x1,long y1,long x2,long y2,long x3,long y3,long x4,long y4) LIBRARY "Gdi32.dll"
Script:
Boolean rtn
ulong l_handle,l_device
long lv[8]
lv[ ] = {10,50,290,220,0,0,80,0}
l_handle = handle(w_main)
l_device = GetDC(l_handle)
rtn = Pie(l_device,lv[1],lv[2],lv[3],lv[4],lv[5],lv[6],lv[7],lv[8])
Polygon( )
이 함수는 주어진 좌표를 이용하여 도형에 기반한 타원을 그립니다.
Global External Function:
FUNCTION boolean Polygon(hdc, ref struct poly poly2, int cnt) LIBRARY "Gdi32.dll"
Structure: (Poly)
long xpos[5], long ypos[5] //The size of the array is proportional to the number of sides in the Polygon.
Script:
ulong l_handle, l_device
int pcnt
l_handle = handle(w_main)
l_device = GetDC(l_handle)
pcnt = 5
poly poly3
poly3.xpos[ ] = {50,100,150,200,250}
poly3.ypos[ ] = {50,100,150,200,250}
Polygon(l_device,poly3,pcnt)
PostMessageA( )
이 함수는 지정된 윈도우에 의해서 만들어진 thread와 관련된 메시지(minimize, close)를 message queue에 post하며 이것이 처리되기전까지는 return되지 않는다.
Global External Function:
FUNCTION boolean PostMessageA(ulong hwndle,UINT wmsg,ulong wParam,ulong lParam) Library "User32.dll"
Script:
ulong l_handle
boolean rtn
l_handle = handle(w_main)
rtn = PostMessageA(l_handle,274,61472,0) // 61472 = minimize, 61488 = maximize, 61728 = normal state
Rectangle( )
이 함수는 주어진 좌표에 의해서 사각형을 그린다.
Global External Function:
FUNCTION boolean Rectangle(ulong hwnd,long x1,long y1,long x2,long y2) LIBRARY "Gdi32.dll"
Script:
Boolean rtn
ulong l_handle,l_device
long lv[4]
lv[ ] = { 10,10,275,215}
l_handle = handle(w_main)
l_device = GetDC(l_handle)
rtn = Rectangle(l_device,lv[1],lv[2],lv[3],lv[4])
SendMessageA( )
이 함수는 지정된 윈도우에 의해서 만들어진 thread와 관련된 message를 message queue에 보내며 그 message가 처리될때까지 return되지 않는다.
Global External Function:
FUNCTION long SendMessageA(ulong hwndle,UINT wmsg,ulong wParam,ulong lParam) Library "User32.dll"
Script:
ulong l_handle
long rtn
l_handle = handle(w_main)
rtn = SendMessageA(l_handle,274,61728,0)
SetCapture( )
이 함수들은 같이 사용되며, SetCapture()함수는 ReleaseCapture()가 호출될때까지 마우스에 락을 건다.
Global External Function:
FUNCTION ulong SetCapture(ulong a) LIBRARY "User32.dll"
FUNCTION boolean ReleaseCapture( ) LIBRARY "User32.dll"
Script:
boolean rtn
ulong l_loop, u_test, u_long
u_test = handle(parent)
u_long = SetCapture(u_test)
SetPointer(SizeNWSE!)
for l_loop = 1 to 150000
next
rtn = ReleaseCapture( )
SetComputerNameA( )
이 함수는 컴퓨터(다른 컴퓨터에서 참조되는)의 이름을 변경한다.
Global External Function:
FUNCTION boolean SetComputerNameA(ref string cname) LIBRARY "kernel32.dll"
Script:
boolean rtn
string l_name
l_name = "Powerbuilder"
rtn = SetComputerNameA(l_name)
if rtn then
MessageBox("Computer name changed to 'Powerbuilder'", "You'll need to reboot for it to take effect")
else
MessageBox("SetComputerName", "Failed")
end if
SetCurrentDirectoryA( )
이 함수는 O/S가 가리키고 있는 현재의 디렉토리를 변경한다. 파워빌더에는 이와 유사한 함수가 없다.
Global External Function:
FUNCTION boolean SetCurrentDirectoryA(ref string cdir) LIBRARY "kernel32.dll"
Script:
boolean rtn
string l_dir
l_dir = "c:\My Documents"
rtn = SetCurrentDirectoryA(l_dir)
MessageBox("SetCurrentDirectory", string(rtn))
SetFocus( )
주어진 윈도우 또는 오브젝트로 포커스를 변경하는 기능을 수행한다. 파워빌더의 오브젝트.SetFocus( )와 유사하다.
Global External Function:
SUBROUTINE SetFocus(long objhandle) LIBRARY "User32.dll"
Script:
SetFocus(handle(sle_1)) // This function gets the handle from PB.
SetThreadPriority( )
이 함수는 주어진 thread의 우선순위를 set한다. default값은 0이며, 그 어떤 높은 우선순위도 hold상태가 되어 더 많은 cpu time을 받을 수 있다. 우선 순위를 너무 높게 잡거나 마우스가 작동하지 않도록 하는 것은 좋지 않다.
Global External Function:
FUNCTION boolean SetThreadPriority(ulong hthread, int npriority) LIBRARY "Kernel32.dll"
Script:
ulong l_handle
boolean rtn
l_handle = GetCurrentThread()
rtn = SetThreadPriority(l_handle, 2) // Set the priority of thread higher.
MessageBox("Current Thread Priority Changed", string(rtn))
Sleep( )
이 함수는 O/S가 주어진 시간(milliseconds)동안 현재의 thread를 무시하도록 한다. 이 함수가 Active상태인 동안 화면은 다시 그려지지 않는다.
Global External Function:
SUBROUTINE Sleep(ulong milli) LIBRARY "Kernel32.dll"
Script:
ulong l_delay
l_delay = 2000
Sleep(l_delay)
SndPlaySoundA( ) & WaveOutGetNumDevs( )
이 함수들은 WAV파일을 파워빌더에서 플레이 한다. 파워빌더에는 이와 유사한 함수가 없다.
Global External Function:
FUNCTION boolean SndPlaySoundA(string wavfile, uint flag) LIBRARY "WINMM.DLL"
FUNCTION uint WaveOutGetNumDevs() LIBRARY "WINMM.DLL"
Script:
int lui_NumDevs, l_mode
string ls_file
l_mode = 0
ls_file = string(c:\windows\media\chimes.wav)
lui_NumDevs = WaveOutGetNumDevs()
IF lui_NumDevs > 0 THEN
SndPlaySoundA(ls_file, l_mode)
END IF
SwapMouseButton( )
이 함수는 마우스의 오른쪽 버튼과 왼쪽 버튼을 서로 바꾸는 일을 하며 파워빌더에는 이와 유사한 함수는 없다. 마우스의 일반(Normal) 상태를 return하기 위해 이 함수는 다시 호출되어야 한다.
Global External Function:
FUNCTION boolean SwapMouseButton(boolean var) LIBRARY "User32.dll"
Script:
boolean rtn, l_mouse
rtn = SwapMouseButton(l_mouse)
If l_mouse = true Then
MessageBox("Change Made","Right button on Left Side")
Else
MessageBox("Change Made","Right button on Right Side")
End If
WinExec( )
이 함수는 주어진 파일명(파일의 경로 포함)을 O/S 트리거에게 전달하며 O/S트리거는 주어진 파일을 실행한후 그 결과를 Return한다. 파워빌더에서는 RUN() 함수를 사용하면 된다.(i.e. Run("c:\windows\calc.exe")
Global External Function:
FUNCTION uint WinExec(ref string filename, uint wstyle) LIBRARY "kernel32.dll"
Script:
string ls_filename
uint rtn, wstyle
ls_filename = "c:\windows\calc.exe"
style = 1
tn = WinExec(ls_filename, wstyle)
Messagebox("Return Code", string(rtn))
[출처] 파워빌더 API함수|작성자 연쓰