Showing posts with label Learn (Belajar) Visual Basic. Show all posts
Showing posts with label Learn (Belajar) Visual Basic. Show all posts

Membuat File Instalasi Untuk Aplikasi Database Delphi Menggunakan Installshield Express

Friday, November 4, 2011 | 11:24 AM|

11:24 AM | 0 comments | Read More

Situs Menyediakan Perintah-Perintah API

Tuesday, May 31, 2011 | 11:40 AM|


Setelah melakukan surfing ke beberapa situs yang khusus membahas perintah-perintah Windows API, nampaknya penulis cukup kewalahan untuk menggabungkan informasi yang disediakan dan menginformasikannya kembali kepada pembaca blog saya ini tentang perintah-perintah API.
Penulis sangat tertarik mempelajari perintah API karena sangat bermanfaat untuk memahami perintah-perintah mesin dan oop (object oriented programming) yang sedikit banyak akan membantu dalam hal pembuatan program dengan skala besar.

Saya sudah pernah menggunakan perintah API dengan Visual Basic 6.0 beberapa tahun yang lalu, dan berhasil membuat beberapa virus yang berhasil menyerang sistem komputer target. Tetapi masih banyak kelemahan dalam program saya itu walaupun cukup membuat saya bangga dengan improvisasi yang saya buat.
Setelah bekerja di pemerintahan, otomatis rutinitas dan hobi saya mengutak-atik perintah dalam bahasa pemrograman dan eksperimen-eksperimen yang saya lakukan selama ini tidak pernah saya lakukan lagi. Sehingga hal tersebut membuat saya menjadi sama sekali tidak memahami perintah API ditambah buku yang saya koleksi tentang perintah-perintah API tidak tau kemana batang hidungnya sekarang.

Hari ini, saya menginggalkan sedikir rutinitas pekerjaan di kantor dengan mencuri-curi waktu untuk bermain internet. Dan terang saja, saya langsung mencari perintah-perintah API menggunakan om google. Banyak sekali memang blog maupun situs yang menampilkan perintah-perintah dan cara penggunaannya dalam visual basic. Tetapi tetap saja saya masih bingung, untuk itu saya sarankan kepada teman-teman yang sekarang telah memahami dan mengerti bahasa pemrograman, jangan pernah meninggalkannya dan sering-seringlah mengulas kembali walaupun rutinitas dan pekerjaan anda sekarang tidak berhubungan dengan bahasa pemrograman.
Sangat disayangkan, ilmu saya selama ini (walaupun secuil) hilang begitu saja [ :( ] .
Bagi teman-teman yang masih aktif menulis program dan mau bereksplorasi dengan perintah API, saya sarankan untuk membuka referensi di http://www.ex-designz.net/apicat.asp?apicat=1 atau klik disini

Sekian dulu ya teman-teman, jika anda masih kesulitan dan mau mengajak saya sharing, saya sangat welcome. Anda bisa memasukkan komentar anda di blog saya ini, dan kita bisa saling kontak.. OKay....
11:40 AM | 0 comments | Read More

Perintah Windows API : GetLastError


API Explanation
GetLastError returns the error code returned by the last API function called. Most API functions merely return a number saying if an error occured, but not what kind of error. This function will return a universal error code identifying the type of error that last occured. Note that most functions set the code to 0 (success) if the function completes successfully, erasing the previous error code. Therefore, be sure to check this error code immediately after an error is found.

Parameter Information
Declare Function GetLastError Lib "kernel32.dll" () As Long

Kode

' Demonstrate catching an invalid handle error
Dim retval As Long ' return value of function
Dim errorcode As Long ' error code

' Make an invalid call to the following function by giving it an invalid handle
retval = CloseHandle(-1) ' there is no handle -1!
If retval = 0 Then ' the return value will be 0 if an error occured
errorcode = GetLastError() ' find the error code
If errorcode = 6 Then Debug.Print "ERROR: Invalid Handle Specified" ' error 6 = invalid handle
End If
11:38 AM | 0 comments | Read More

Perintah WIndows API untuk membuat Sleep pada Komputer


API Explanation
Sleep pauses program execution for a certain amount of time. This is more accurate than using a do-nothing loop, waiting for a certain amount of time to pass. The function does not return a value.

Parameter Information
Declare Sub Sleep Lib "kernel32.dll" (ByVal dwMilliseconds As Long)

dwMilliseconds
The number of milliseconds to halt program execution for.

Kode :

' Pause the program for 2 seconds, displaying the system
' time before and after the pause.

Debug.Print "The time is "; Time$ ' display the current time
Sleep 2000 ' 2000 milliseconds = 2 seconds to delay
Debug.Print "The time is "; Time$ ' this time will be 2 seconds later
11:29 AM | 0 comments | Read More

Mengunci Software Update Windows dengan Perintah Windows API


API Explanation
Use the LockWindowUpdate API to help speed up your app and eliminate annoying flickering. This is an extremely easy API to use. Just one declaration, one line of code to turn it on, and one line of code to turn it off. Using this API will prevent your form from receiving any refresh messages from windows. It is best not to use this function for long processes since your form will not be repainted until you turn it off.

Parameter Information
Declare Function LockWindowUpdate Lib "user32" (ByVal hWnd As Long) As Long

Kode :



Declare Function LockWindowUpdate Lib "user32" (ByVal hWnd As Long) As Long

'To turn it on just call it like this, passing it the hWnd of the window to lock.
LockWindowUpdate Form1.hWnd
'To turn it off just call it and pass it a zero.
LockWindowUpdate 0


11:28 AM | 0 comments | Read More

Mengaktifkan Fungsi Tombol Escape dengan Perintah API

API Explanation
The Escape function allows applications to access capabilities of a particular device not directly available through GDI. Escape calls made by an application are translated and sent to the driver

Parameter Information
Declare Function Escape Lib "gdi32" Alias "Escape" (ByVal hdc As Long, ByVal nEscape As Long, ByVal nCount As Long, ByVal lpInData As String, lpOutData As Any) As Long


· hdc
Identifies the device context.

· nEscape
Specifies the escape function to be performed. This parameter must be one of the predefined escape values. Use the ExtEscape function if your application defines a private escape value.

· cbInput
Specifies the number of bytes of data pointed to by the lpvInData parameter.

· lpvInData
Points to the input structure required for the specified escape.

· lpvOutData
Points to the structure that receives output from this escape. This parameter should be NULL if no data is returned.

If the function succeeds, the return value is greater than zero, except with the QUERYESCSUPPORT printer escape, which checks for implementation only. If the escape is not implemented, the return value is zero.

If the function fails, the return value is an error. To get extended error information, call GetLastError.


Kode dalam Form :


Const NEWFRAME = 1
Private Declare Function Escape Lib "gdi32" (ByVal hdc As Long, ByVal nEscape As Long, ByVal nCount As _ Long, ByVal lpInData As String, lpOutData As Any) As Long
Private Declare Function CreateCompatibleDC Lib "gdi32" (ByVal hdc As Long) As Long
Private Declare Function SelectObject Lib "gdi32" (ByVal hdc As Long, ByVal hObject As Long) As Long
Private Declare Function StretchBlt Lib "gdi32" (ByVal hdc As Long, ByVal x As Long, ByVal y As Long, ByVal _ nWidth As Long, ByVal nHeight As Long, ByVal hSrcDC As Long, ByVal xSrc As Long, ByVal ySrc _ As Long, ByVal nSrcWidth As Long, ByVal nSrcHeight As Long, ByVal dwRop As Long) As Long
Private Declare Function DeleteDC Lib "gdi32" (ByVal hdc As Long) As Long
Dim hMemoryDC As Long

Private Sub Command1_Click()
'API uses pixels
Picture1.ScaleMode = vbPixels
Printer.ScaleMode = vbPixels
'Take paper
Printer.Print ""

'Create a compatible device context
hMemoryDC = CreateCompatibleDC(Picture1.hdc)
'Select Picture1's picture into our new device context
hOldBitMap = SelectObject(hMemoryDC, Picture1.Picture)

'Stretch our picture to the height and width of the paper
StretchBlt Printer.hdc, 0, 0, Printer.ScaleWidth, Printer.ScaleHeight, hMemoryDC, 0, 0, _
Picture1.ScaleWidth, Picture1.ScaleHeight, vbSrcCopy

'Select the original bitmap into our DC
hOldBitMap = SelectObject(hMemoryDC, hOldBitMap)
'Delete our memorydc
DeleteDC hMemoryDC

'Access our printer device
Escape Printer.hdc, NEWFRAME, 0, 0&, 0&

'End of document
Printer.EndDoc
End Sub
11:27 AM | 0 comments | Read More

Menemukan File Executable dengan Perintah API

Pendeklarasian Perintah API :
API Explanation
The FindExecutable function retrieves the name and handle to the executable (.EXE) file associated with the specified filename.

Parameter Information
Declare Function FindExecutable Lib "shell32.dll" Alias "FindExecutableA" (ByVal lpFile As String, ByVal lpDirectory _
As String, ByVal lpResult As String) As Long


· lpFile
Pointer to a null-terminated string specifying a filename. This can be a document or executable file.

· lpDirectory
Pointer to a null-terminated string specifying the default directory.

· lpResult
Pointer to a buffer to receive the filename when the function returns. This filename is a null-terminated string specifying the executable file started when an "open" association is run on the file specified in the lpFile parameter.

When FindExecutable returns, the lpResult parameter may contain the path to the DDE server started if no server responds to a request to initiate a DDE conversation.

Kode dalam Form :


Const MAX_FILENAME_LEN = 260
Private Declare Function FindExecutable Lib "shell32.dll" Alias "FindExecutableA" (ByVal lpFile As String, _ ByVal lpDirectory As String, ByVal lpResult As String) As Long

Private Sub Form_Load()
Dim i As Integer, s2 As String
Const sFile = "C:\\Windows\\Readme.txt"

'Check if the file exists
If Dir(sFile) = "" Or sFile = "" Then
MsgBox "File not found!", vbCritical
Exit Sub
End If
'Create a buffer
s2 = String(MAX_FILENAME_LEN, 32)
'Retrieve the name and handle of the executable, associated with this file
i = FindExecutable(sFile, vbNullString, s2)
If i > 32 Then
MsgBox Left$(s2, InStr(s2, Chr$(0)) - 1)
Else
MsgBox "No association found !"
End If
End Sub
11:25 AM | 0 comments | Read More

Aplikasi API untuk mengirim Pesan


API Explanation
N/A

Parameter Information
Public Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hWnd As _
Long, ByVal wMsg As Long, ByVal wParam As _
Long, lParam As Any) As Long

Kode :

Private Sub File1_MouseMove(Button As Integer, Shift As Integer, x As Single, y As Single)
Dim ItemHeight As Long
Dim NewIndex As Long
Static OldIndex As Long

With File1
ItemHeight = SendMessage(.hWnd, LB_GETITEMHEIGHT, 0, ByVal 0&)
ItemHeight = .Parent.ScaleY(ItemHeight, vbPixels, vbTwips)
NewIndex = .TopIndex + (y \\ ItemHeight)
If NewIndex <> OldIndex Then
If NewIndex < .ListCount Then
.ToolTipText = .List(NewIndex)
Else
.ToolTipText = vbNullString
End If
OldIndex = NewIndex
End If
End With
End Sub
11:23 AM | 0 comments | Read More

Belajar Windows API (2)

API (Application Program Interface)
Dalam contoh program sederhana di atas, dibutuhkan setidaknya ribuan system calls per detik. Oleh karena itu Kebanyakan programmer membuat aplikasi dengan menggunakan Application Programming Interface(API). Dalam API itu terdapat fungsi-fungsi/perintah-perintah untuk menggantikan bahasa yang digunakan dalam system calls dengan bahasa yang lebih terstruktur dan mudah dimengerti oleh programmer. Fungsi yang dibuat dengan menggunakan API tersebut kemudian akan memanggil system calls sesuai dengan sistem operasinya. Tidak tertutup kemungkinan nama dari system calls sama dengan nama di API.

Keuntungan memprogram dengan menggunakan API adalah:
Portabilitas. Programmer yang menggunakan API dapat menjalankan programnya dalam sistem operasi mana saja asalkan sudah ter- install API tersebut. Sedangkan system call berbeda antar sistem operasi, dengan catatan dalam implementasinya mungkin saja berbeda.
Lebih Mudah Dimengerti. API menggunakan bahasa yang lebih terstruktur dan mudah dimengerti daripada bahasa system call. Hal ini sangat penting dalam hal editing dan pengembangan.
System call interface ini berfungsi sebagai penghubung antara API dan system call yang dimengerti oleh sistem operasi. System call interface ini akan menerjemahkan perintah dalam API dan kemudian akan memanggil system calls yang diperlukan.
Untuk membuka suatu file tersebut user menggunakan program yang telah dibuat dengan menggunakan bantuan API, maka perintah dari user tersebut diterjemahkan dulu oleh program menjadi perintah open(). Perintah open() ini merupakan perintah dari API dan bukan perintah yang langsung dimengerti oleh kernel sistem operasi. Oleh karena itu, agar keinginan user dapat dimengerti oleh sistem operasi, maka perintah open() tadi diterjemahkan ke dalam bentuk system call oleh system call interface. Implementasi perintah open() tadi bisa bermacam-macam tergantung dari sistem operasi yang kita gunakan.

Windows Aplication Programing Interface
Windows ApI adalah sekumpulan antar muka pemrograman aplikasi yang dibuat oleh Microsoft dalam hal inti sistem operasi Microsoft Windows. Akses terhadap elemen sistem operasi yang lebih rendah, seperti halnya yang dibutuhkan oleh devise driver. Tidak disediakan oleh windows API. Tapi disediakan oleh Windows Driver Foundation atau Native API dalam versi-versi baru Windows baru, Microsoft sering merilis Software Development Kit (SDK), yang terdiri dari dokumentasi dan alat bantu untuk membangun aplikasi-aplikasi windows dengan teknologi terbaru Mocrosoft Windows.

Versi-versi Windows API
1. Win16 API
Windoows 16 API atau winb16 API merupakan API yang digunakan pertama kali pada versi Windows 16-bit. Pada awalnya win16 API disebut dengan windows API, tapi kemudian diubah menjadi win16 dalam usaha Microsoft untuk membedakannya dengan versi windows API yang lebih baru yang berjalan pada windows 32-bit dan win32 API. Meskipun memiliki eksistensi EXE sebenarnya win16 bukan bekas yang dapat dieksekusi melainkan adalah DLL (Dynamic Linking Library)
2. Win32 API
Merupakan antarmuka pemrograman terdapat di dalam sistem operasi windows 32-bit modern, yang antara lain memiliki kernel32.dll, user32.dll dan gdi32.dll.
Windows API-32bit
Windows API (Application Programming Interface) merupakan sekumpulan fungsi-fungsi eksternal yang terdapat dalam file-file perpustakaan Windows (disebut library Windows) atau file library lainnya yang dapat digunakan oleh program. Fungsi ini dapat menangani semua yang berhubungan dengan Windows, seperti pengaksesan disk, interface printer, grafik Windows, kotak dialog (buka file, simpan file, memilih font, memilih warna, dan lain-lain), Windows shell, setting sistem operasi , penanganan file, mengakses sistem registry, memainkan musik, dan sebagainya.
Fungsi menyediakan banyak fitur-fitur standar untuk semua program yang berbasis Windows. Semua fungsi Windows API hampir terdapat dalam direktori sistem milik Windows
(biasanya terdapat dalam direktori C:\Windows\System32 (untuk OS Windows XP), C:\WindowsNT\ System32 (untuk OS Windows NT/2000), dan paling banyak berekstensi DLL yang digunakan oleh sistem operasi Windows. Selain fungsi ini juga memastikan secara konsisten penggunaan semua sumber yang terdapat dalam Windows. File-file itulah yang disebut dengan Windows API. Karena fungsi Windows API merupakan fungsi eksternal, maka untuk menggunakan fungsi tersebut terlebih dahulu dideklarasikan dengan perintah Declare di dalam kode program (pembahasan printah Declare akan dijelaskan nanti dibagian “Mendeklarasikan Fungsi Windows API”). Setelah pendeklarasian fungsi selesai dilakukan, selanjutnya untuk menggunakan fungsi tersebut layaknya Visual Basic di dalam program.

3. Win32sAPI
Merupakan sebuah ekstensi untuk keluargha windows 3.1x yang mengimplementasi kan sekumpulan kecil dari win32 API untuk sistem-sistem tersebut, yang merupakan sistem operasi 16-bit. Huruf “s” merupakan singkatan dari subset.
4. Win32 for 64-bit Windows
Merupakan sebuah versi windows API yang ditargetkan untuk digunakan oleh windows versi64-bit yaitu XP, Profesional dan Server 2003


Berdasarkan Uraian diatas maka dengan adanya WIN API akan memudahkan kita dalam :
1. Membuat user interface baru
2. Membuat jembatan antar aplikasi (misalnya dari MS office ke VB, Delphi atau program lain)
3. Memudahkan kita dalam membuat beberapa tampilan aplikasi kita window seolah seperti bekerja secara bersamaan. Misalnya dari Program Words ke musik, games atau ke film ataupun ke program aplikasi lainya.
11:16 AM | 0 comments | Read More

Belajar Windows API (1)


Meskipun konsepnya sama, tiap-tiap sistem operasi memiliki nama atau istilah yang berbeda untuk CLI-nya. UNIX memberi nama CLI-nya sebagai bash, ash, ksh, dan lain sebagainya. Microsoft Disk Operating System (MS-DOS) memberi nama command.com atau Command Prompt. Sedangkan pada Windows Vista, Microsoft menamakannya PowerShell. Pengguna Linux mengenal CLI pada Linux sebagai terminal, sedangkan pada Apple namanya adalah commandshell.
Graphical User Interface(GUI)
GUI adalah tipe antarmuka yang digunakan oleh pengguna untuk berinteraksi dengan sistem operasi melalui gambar-gambar grafik, ikon, menu, dan menggunakan perangkat penunjuk ( pointing device) seperti mouse atau track ball. Elemen-elemen utama dari GUI bisa diringkas dalam konsep WIMP ( window, icon, menu, pointing device)

Pengguna komputer yang awam seringkali menilai sebuah sistem operasi dari GUI-nya. Sebuah sistem operasi dianggap bagus jika tampilan luarnya (GUI-nya) bagus. Padahal, seperti telah dijelaskan sebelumnya, komponen sistem operasi tidak hanya GUI, sehingga penilaian terhadap sebuah sistem operasi tidak bisa hanya dari satu komponen saja. Karena GUI adalah kesan pertama pengguna dengan sistem operasi itu, setiap pengembang sistem operasi berlomba-lomba mengembangkan GUI-nya dengan keunggulannya masing-masing.
Sejarah mencatat bahwa Xerox PARC (Palo Alto Research Center) yang pertama kali meriset tentang GUI. Pada tahun 1984, Apple merilis Macintosh yang menggunakan GUI hasil riset Xerox PARC. Beberapa tahun kemudian, Microsoft merilis sistem operasi Windows-nya yang juga menggunakan GUI. Apple mengklaim bahwa Microsoft mencuri ide dari Apple.
Seperti halnya CLI, tiap-tiap sistem operasi juga memiliki nama tersendiri untuk komponen GUI-nya. Pada Apple Mac OS X, GUI-nya disebutAqua. Microsoft memberi nama GUI Windows XP sebagai Lunar dan GUI Windows Vista sebagai Aero. Pada Linux, ada dua pengembang utama desktop environment pada Linux, yang masing-masing menghasilkan produk KDE (K Desktop Environment) dan GNOME. KDE digunakan pada beberapa distro seperti SuSE dan Mandrake, sedangkan GNOME dipakai pada beberapa distro seperti Fedora Core dan Ubuntu.
System Calls
Komputer digunakan untuk melakukan suatu proses yang dikehendaki user. Oleh karena itu harus ada suatu bentuk komunikasi antara user dan hardware. Komunikasi itu terjadi dalam bentuk system calls. SO melalui shell-nya akan menangkap perintah dari user yang kemudian akan dikomunikasikan melalui system calls. Disinilah peran SO sebagai jembatan komunikasi antara user dan hardware itu terjadi. System calls itu sendiri umumnya ditulis dalam bahasa C dan C++.
Mengenai shell, shell itu sendiri secara umum adalah layer yang berfungsi sebagai interface antara user dan inti dalam sistem operasi (kernel). Melalui shell, user dapat memberi perintah-perintah yang akan dikirim ke sistem operasi, sehingga shell ini merupakan layer yang menerima interaksi dari user secara langsung. Shell dalam SO secara umum dibagi menjadi 2, Command Line(CLI) dan Graphical(GUI). Jadi dengan kata lain, system calls berperan sebagai interface dalam layanan-layanan yang disediakan oleh sistem operasi.
Untuk lebih jelasnya lihat gambar berikut. Contoh di atas adalah sytem calls di dalam program yang membaca data dari satu file lalu meng- copy-nya ke file lain.
11:09 AM | 0 comments | Read More

Penggunaan fungsi Win32-API pada Visual Basic


Prosedur-prosedur yang terdapat pada Win32-API, dapat membantu kita dalam membuat program yang mengandung perintah-perintah yang terdapat pada Windows namun tidak tersedia pada VB, misalkan seperti fungsi untuk copy file, move file, pengaturan dekstop, dan lain-lain.

Berikut ini merupakan contoh sederhana penggunaan Win32-API pada Visual Basic. Pada kasus ini, kita akan membuat program sederhana dengan tampilan seperti windows explorer dan fungsi copy paste file.

Source code secara lengkap dapat di download di sini

Code yang dituliskan pada jendela modul:
Declare Function CopyFile Lib “kernel32″ Alias “CopyFileA” (ByVal lpExistingFileName As String, ByVal lpNewFileName As String, ByVal bFailIfExists As Long) As Long Declare Function CopyFile Lib “kernel32″ Alias “CopyFileA” (ByVal
lpExistingFileName As String, ByVal lpNewFileName As String, ByVal bFailIfExists As Long) As Long

Code yang dituliskan pada listing program:
Dim nFile As String
Dim pFile As String
Dim FileC, FileCP As String
Const APP_TITLE = “Explorer “

Private Sub Command1_Click()
‘untuk mendapatkan nama file yg akan di copy
FileC = nFile
‘path file yang akan dicopy
FileCP = pFile
‘mengaktifkan tombol paste
Command2.Enabled = True
End Sub

Private Sub Command2_Click()
Dim A As Long
A = CopyFile(FileCP & “\” & FileC, pFile & “\” & FileC, True)
If A Then
MsgBox “File sudah dicopy !”, vbOKOnly, “Copy File”
File1.Refresh
Else
MsgBox “File gagal dicopy !”, vbOKOnly, “Copy File”
End If
End Sub

Private Sub Dir1_Change()
File1.Path = Dir1.Path
Label2.Caption = Dir1.Path
pFile = Dir1.Path
End Sub

Private Sub Drive1_Change()
If Drive1.Drive = “a:” Then
Exit Sub
End If
Form1.Caption = APP_TITLE & Drive1.Drive
Dir1.Path = Drive1.Drive
End Sub

Private Sub File1_Click()
‘untuk mendapatkan nama file beserta tipe file yang di klik (di pilih)
nFile = File1.List(File1.ListIndex)
Label1.Caption = nFile
Command1.Enabled = True
End Sub

Private Sub Form_Load()
Form1.Caption = APP_TITLE & Drive1.Drive
Dir1.Path = Drive1.Drive
File1.Path = Dir1.Path
Command1.Enabled = False
Command2.Enabled = False
End Sub

Code pada command1 digunakan untuk mendapatkan nama dan path file yang akan di copy. Dan pada command2, terdapat fungsi untuk Copy file yang telah dideklarasikan sebelumnya pada jendela modul.
Bentuk umum dari perintah CopyFile tersebut yaitu:
CopyFile([path_file]\[nama_file], [path_file_baru]\[nama_file_baru],[true|false])
Contoh:
CopyFile(C:\File.doc, C:\Dir\File.doc, False)
Artinya yaitu mengcopy File.doc dari drive C ke folder Dir. Jika file.doc sudah ada pada folder Dir, maka ia akan overwrite file tersebut. Untuk melewatkannya, ganti False menjadi True.

10:50 AM | 0 comments | Read More

Tentang Windows API


Untuk keperluan pengembangan aplikasi berbasis Windows yang handal, Microsoft menciptakan sebuah antarmuka (interface) pemrograman berupa sekumpulan prosedur dan rutin yang memiliki kemampuan mengakses kekuatan sistem. Sekumpulan prosedur dan rutin tersebut kemudian dikenal dengan istilah Aplication Programming Interface atau yang lebih familiar dengan sebutan API.
Pada saat Windows diciptakan oleh Microsoft, sesungguhnya Microsoft menempatkan sejumlah besar kode siap pakai pada pustaka sistemnya sehingga dapat diakses oleh programmer lainnya. Kode siap pakai tersebut berupa sekumpulan rutin dan fungsi yang dikenal sebagai “API Functions”.
Programmer-programmer Windows menulis file .dll (dynamic link library) untuk melakukan tugas-tugas yang bersifat pemeliharaan (maintenance) sistem dan perintah-perintah computer tingkat rendah (Low-end System task), agar dapat digunakan oleh berbagai aplikasi yang ter-instal pada computer.
Setiap tugas (task) yang dilakukan oleh Windows dalam setiap proses kerjanya, sering memanfaatkan fungsi API yang berada di dalam file .dll. Terdapat banyak file .dll yang terdapat pada direktori %SystemRoot%, dan umunya berada pada C:\[Windows|Winnt]\[System|System32]. Beberapa file .dll yang sering digunakan untuk membantu pemrograman yang dibuat adalah:
User32.dll. File ini digunakan untuk mengontrol objek-objek yang terlihat pada layar.
Gdi32.dll. Merupakan gudang kode pemrograman berorientasi grafik dari API.
Kernel32.dll. Di dalamnya terdapat fitur-fitur untuk mengakses sistem operasi tingkat bawah. Dengan kernel32.dll kita dapat melakukan berbagai macam manipulasi pada system Windows. Namun, kita harus hati-hati dalam menggunakan file ini, karena sistem akan crash jika ceroboh dalam menggunakannya.

Sumber: Johan Saputra. Eksplorasi Kekuatan WIN32-API dengan Visual Basic
10:38 AM | 0 comments | Read More

Perintah Visual Basic untuk memanggil database dari Access

Tuesday, December 22, 2009 | 10:57 AM|


Berikut ini adalah sedikit tulisan yang dapat digunakan untuk memanggil database dari microsoft access dari bahasa pemrograman visual basic 6.0.
Perintah ini sangat sederhana tetapi sangat membantu bagi pembuatan program berbasis database. Nantinya penulis akan membuat tulisan bagaimana cara menghubungkan 2 komputer menggunakan data base microsoft access sehingga link antara satu komputer dengan komputer lain dapat terjalin. Untuk itu kita nantinya akan membahas perintah-perintah SQL secara fundamental dan Advanced nya yang akan disajikan secara sederhana.
Sebelum kesana berikut ini adalah langkat-langkah untuk memanggil database microsoft access yang dimaksudkan.


Memanggil Database
Database yang digunakan acces dengan objek Data, anda tidak perlu merubah setingan pada properties cukup ketikkan code dibawah!

Data1.RecordSource = “select *from (nama tabel) in’” _
& DatabaseName & “‘”
Data1.DatabaseName = App.Path + “\(nama file).mdb”
Data1.Refresh

Fungsi app.path untuk memanggil file acces yang berada satu folder dengan file VB jadi sebelum menjalankan program simpan terlebih dahulu file VB anda satu folder dengan file acces.
Setingan code di modifikasi tergantung dimana anda ingin menyimpan file acces, tidak harus satu folder.

Mensortir Data
Pensortiran data digunakan agar anda dapat mensortir tampilan data sesuai yang inginkan.

Data1.RecordSource = “select *from (nama tabel) in’” _
& DatabaseName & ” order by (nama field)”
Data1.DatabaseName = App.Path + “\(nama file).mdb”
Data1.Refresh

Dengan menambahkan syntax order by maka anda dapat mensortir data. Sytax di atas pun masih bisa anda modifikasi dengan sortir ascending atau descending juga dapat dimodifikasi menjadi sebuah masukkan (variabel) yang tidak anda definisikan sebelumnya. Dengan ini anda dapat melakukan pensortiran berbagai record ketika program dijalankan ^^

Menseleksi Data
Penseleksian juga berguna sebagai pencarian data, seperti yang sering saya lakukan.

Data2.RecordSource = “select *from (nama tabel) in’” _
& DatabaseName & “‘ where (nama field) like ‘” & (x) & “‘”
Data2.DatabaseName = App.Path + “\(nama file).mdb”
Data2.Refresh

where like ‘” & (x) & “‘ berfungsi sebagai mesin seleksi data. x tersebut merupakan kriteria penseleksian yang diinginkan. x dapat dimodifikasi menjadi sebuah masukkan yang akhirnya berfungsi sebagai pencarian. Syntax di atas merupakan penseleksian tipe eksak, artinya jika kriteria penseleksian adalah string aku maka akan hanya akan tampil record aku bukan yang mengandung kata aku. Dengan menambahkan ‘*” & (x) & “*’ maka fungsinya berubah dari eksak menjadi yang mengandung ^^

Pemanfaatan Operator and dan or Pada Seleksi Data
Operator and dan or berguna jika anda ingin melakukan penseleksian dengan kondisi dua atau lebih.

Data1.RecordSource = “select *from (nama tabel) in’” _
& DatabaseName & “‘ where (nama field) like ‘” & (x) & “‘ _
and (nama field2) like ‘” & (x2) & “‘”
Data1.DatabaseName = App.Path + “\(nama file).mdb”
Data1.Refresh

silahkan diganti and dengan or atau bisa juga ditambahkan.
Sekian dulu kali ya, sambung next time ^o^
10:57 AM | 5 comments | Read More

Belajar pemrograman (Sejarah JAVA eps1)

Wednesday, August 5, 2009 | 4:30 PM|

Latar Belakang Bahasa JAVA

Pada 1991, sekelompok insinyur Sun dipimpin oleh Patrick Naughton dan James
Gosling ingin merancang bahasa komputer untuk perangkat konsumer seperti cable
TV Box. Dikarenakan perangkat tersebut tidak memiliki banyak memori, bahasa
harus berukuran kecil dan mengandung kode yang liat. Juga karena manufakturmanufaktur
berbeda memilih processor yang berbeda pula, maka bahasa harus
bebas dari manufaktur manapun. Proyek diberi nama kode ”Green”.
Kebutuhan untuk fleksibilitas, kecil, liat dan kode yang netral terhadap platform
mengantar tim mempelajari implementasi Pascal yang pernah dicoba. Niklaus Wirth,
pencipta bahasa Pascal telah merancang bahasa portabel yang menghasilkan
intermediate code untuk mesin hipotesis. Mesin ini sering disebut dengan mesin
maya (virtual machine). Kode ini kemudian dapat digunakan di sembarang mesin
yang memiliki interpreter. Proyek Green menggunakan mesin maya untuk mengatasi
isu utama tentang netral terhadap arsitektur mesin.
Karena orang–orang di proyek Green berbasis C++ dan bukan Pascal maka
kebanyakan sintaks diambil dari C++, serta mengadopsi orientasi objek dan bukan
prosedural. Mulanya bahasa yang diciptakan diberi nama ”Oak” oleh James Gosling
yang mendapat inspirasi dari sebuah pohon yang berada pada seberang kantornya,
namun dikarenakan nama Oak sendiri merupakan nama bahasa pemrograman yang
telah ada sebelumnya, kemudian SUN menggantinya dengan JAVA. Nama JAVA
sendiri terinspirasi pada saat mereka sedang menikmati secangkir kopi di sebuah
kedai kopi yang kemudian dengan tidak sengaja salah satu dari mereka
menyebutkan kata JAVA yang mengandung arti asal bijih kopi. Akhirnya mereka
sepakat untuk memberikan nama bahasa pemrograman tersebut dengan nama Java.
Produk pertama proyek Green adalah Star 7 (*7), sebuah kendali jarak jauh yang
sangat cerdas. Dikarenakan pasar masih belum tertarik dengan produk konsumer
cerdas maka proyek Green harus menemukan pasar lain dari teknologi yang
diciptakan. Pada saat yang sama, implementasi WWW dan Internet sedang
mengalami perkembangan pesat. Di lain pihak, anggota dari proyek Green juga
menyadari bahwa Java dapat digunakan pada pemrograman internet, sehingga
penerapan selanjutnya mengarah menjadi teknologi yang berperan di web.

Java telah mengakomodasi hampir seluruh fitur penting bahasa–bahasa
pemrograman yang ada semenjak perkembangan komputasi modern manusia :
1.Dari SIMULA, bahasa pada tahun 65-an, bahasa yang paling mempengaruhi
Java sekaligus C++. Dari bahasa ini diadopsi bentukan–bentukan dasar dari
pemrograman berorientasi objek.
2. Dari LISP – bahasa tahun 55-an. Diadopsi fasilitas garbage collection, serta
kemampuan untuk meniru generic list processing, meski fasilitas ini jarang
yang memanfaatkannya.
3. Dari Algol – bahasa pada tahun 60-an, diambil struktur kendali yang
dimilikinya.
4. Dari C++, diadopsi sintaks, sebagian semantiks dan exception handling
5. Dari bahasa Ada, diambil strongly type, dan exception handling.
6. Dari Objective C, diambil fasilitas interface.
7. Dari bahasa SmallTalk, diambil pendekatan single-root class hiérarchie,
dimana object adalah satu kesatuan hirarki pewarisan
8. Dari bahasa Eiffel, fasilitas assertion yang mulai diterapkan di sebagian JDK
1.4



4:30 PM | 0 comments | Read More

Apa itu Teknologi JAVA?


Sebagai sebuah bahasa pemrograman, Java dapat membuat seluruh bentuk aplikasi,
desktop, web dan lainnya, sebagaimana dibuat dengan menggunakan bahasa
pemrograman konvensional yang lain.
Java adalah bahasa pemrograman yang berorientasi objek (OOP) dan dapat
dijalankan pada berbagai platform sistem operasi. Perkembangan Java tidak hanya
terfokus pada satu sistem operasi, tetapi dikembangkan untuk berbagai sistem
operasi dan bersifat open source.

Sebuah Development Environment
Sebagai sebuah peralatan pembangun, teknologi Java menyediakan banyak tools :
compiler, interpreter, penyusun dokumentasi, paket kelas dan sebagainya.
Sebuah Aplikasi
Aplikasi dengan teknologi Java secara umum adalah aplikasi serba guna yang dapat
dijalankan pada seluruh mesin yang memiliki Java Runtime Environment (JRE).
Sebuah Deployment Environment
Terdapat dua komponen utama dari Deployment Environment. Yang pertama adalah
JRE, yang terdapat pada paket J2SDK, mengandung kelas–kelas untuk semua paket
teknologi Java yang meliputi kelas dasar dari Java, komponen GUI dan sebagainya.
Komponen yang lain terdapat pada Web Browser. Hampir seluruh Web Browser
komersial menyediakan interpreter dan runtime environment dari teknologi Java.


4:27 PM | 0 comments | Read More

Belajar Pemrograman Java Eps 2(Mengapa Mempelajari JAVA?)

Mengapa Mempelajari JAVA?
Berdasarkan white paper resmi dari SUN, Java memiliki karakteristik berikut :
1. Sederhana
Bahasa pemrograman Java menggunakan sintaks mirip dengan C++ namun
sintaks pada Java telah banyak diperbaiki terutama menghilangkan
penggunaan pointer yang rumit dan multiple inheritance. Java juga
menggunakan automatic memory allocation dan memory garbage collection.
2. Berorientasi objek (Object Oriented)
Java mengunakan pemrograman berorientasi objek yang membuat program
dapat dibuat secara modular dan dapat dipergunakan kembali. Pemrograman
berorientasi objek memodelkan dunia nyata kedalam objek dan melakukan
interaksi antar objek-objek tersebut.


3. Dapat didistribusi dengan mudah
Java dibuat untuk membuat aplikasi terdistribusi secara mudah dengan adanya
libraries networking yang terintegrasi pada Java.
4. Interpreter
Program Java dijalankan menggunakan interpreter yaitu Java Virtual Machine
(JVM). Hal ini menyebabkan source code Java yang telah dikompilasi menjadi
Java bytecodes dapat dijalankan pada platform yang berbeda-beda.
5. Robust
Java mempuyai reliabilitas yang tinggi. Compiler pada Java mempunyai
kemampuan mendeteksi error secara lebih teliti dibandingkan bahasa
pemrograman lain. Java mempunyai runtime-Exception handling untuk
membantu mengatasi error pada pemrograman.
6. Aman
Sebagai bahasa pemrograman untuk aplikasi internet dan terdistribusi, Java
memiliki beberapa mekanisme keamanan untuk menjaga aplikasi tidak
digunakan untuk merusak sistem komputer yang menjalankan aplikasi
tersebut.
7. Architecture Neutral
Program Java merupakan platform independent. Program cukup mempunyai
satu buah versi yang dapat dijalankan pada platform yang berbeda dengan
Java Virtual Machine.
8. Portabel
Source code maupun program Java dapat dengan mudah dibawa ke platform
yang berbeda-beda tanpa harus dikompilasi ulang.
9. Performance
Performance pada Java sering dikatakan kurang tinggi. Namun performance
Java dapat ditingkatkan menggunakan kompilasi Java lain seperti buatan
Inprise, Microsoft ataupun Symantec yang menggunakan Just In Time
Compilers (JIT).
10. Multithreaded
Java mempunyai kemampuan untuk membuat suatu program yang dapat
melakukan beberapa pekerjaan secara sekaligus dan simultan.
11. Dinamis
Java didesain untuk dapat dijalankan pada lingkungan yang dinamis. Perubahan
pada suatu class dengan menambahkan properties ataupun method dapat
dilakukan tanpa menggangu program yang menggunakan class tersebut.
Sebagian Fitur dari JAVA
Java Virtual Machine (JVM)
JVM adalah sebuah mesin imajiner (maya) yang bekerja dengan menyerupai aplikasi
pada sebuah mesin nyata. JVM menyediakan spesifikasi hardware dan platform
dimana kompilasi kode Java terjadi. Spesifikasi inilah yang membuat aplikasi
berbasis Java menjadi bebas dari platform manapun karena proses kompilasi
diselesaikan oleh JVM.
Aplikasi program Java diciptakan dengan file teks berekstensi .java. Program ini
dikompilasi menghasilkan satu berkas bytecode berekstensi .class atau lebih.
Bytecode adalah serangkaian instruksi serupa instruksi kode mesin. Perbedaannya
adalah kode mesin harus dijalankan pada sistem komputer dimana kompilasi
ditujukan, sementara bytecode berjalan pada java interpreter yang tersedia di
semua platform sistem komputer dan sistem operasi.
Garbage Collection
Banyak bahasa pemrogaman lain yang mengijinkan seorang programmer
mengalokasikan memori pada saat dijalankan. Namun, setelah menggunakan alokasi
memori tersebut, harus terdapat cara untuk menempatkan kembali blok memori
tersebut supaya program lain dapat menggunakannya. Dalam C, C++ dan bahasa
lainnya, adalah programmer yang mutlak bertanggung jawab akan hal ini. Hal ini
dapat menyulitkan bilamana programmer tersebut alpa untuk mengembalikan blok
memori sehingga menyebabkan situasi yang dikenal dengan nama memory leaks.
Program Java melakukan garbage collection yang berarti program tidak perlu
menghapus sendiri objek–objek yang tidak digunakan lagi. Fasilitas ini mengurangi
beban pengelolaan memori oleh programmer dan mengurangi atau mengeliminasi
sumber kesalahan terbesar yang terdapat pada bahasa yang memungkinkan alokasi
dinamis.
Code Security
Code Security terimplementasi pada Java melalui penggunaan Java Runtime
Environment (JRE). Java menggunakan model pengamanan 3 lapis untuk melindungi
sistem dari untrusted Java Code.
1. Pertama, class-loader menangani pemuatan kelas Java ke runtime
interpreter. Proses ini menyediakan pengamanan dengan memisahkan kelas–
kelas yang berasal dari local disk dengan kelas–kelas yang diambil dari
jaringan. Hal ini membatasi aplikasi Trojan karena kelas–kelas yang berasal
dari local disk yang dimuat terlebih dahulu.
2. Kedua, bytecode verifier membaca bytecode sebelum dijalankan dan
menjamin bytecode memenuhi aturan–aturan dasar bahasa Java.
3. Ketiga, manajemen keamanan menangani keamanan tingkat aplikasi dengan
mengendalikan apakah program berhak mengakses sumber daya seperti
sistem file, port jaringan, proses eksternal dan sistem windowing.
Setelah seluruh proses tersebut selesai dijalankan, barulah kode program di
eksekusi.
Java juga menyediakan beragam teknik pengamanan lain :
1. Bahasa dirancang untuk mempersulit eksekusi kode perusak. Peniadaan
pointer merupakan langkah besar pengamanan. Java tidak mengenal operasi
pointer. Di tangan programmer handal, operasi pointer merupakan hal yang
luar biasa untuk optimasi dan pembuatan program yang efisien serta
mengagumkan. Namun mode ini dapat menjadi petaka di hadapan
programmer jahat. Pointer merupakan sarana luar biasa untuk pengaksesan
tak diotorisasi. Dengan peniadaan operasi pointer, Java dapat menjadi bahasa
yang lebih aman.
2. Java memiliki beberapa pengaman terhadap applet. Untuk mencegah
program bertindak mengganggu media penyimpanan, maka applet tidak
diperbolehkan melakukan open, read ataupun write terhadap berkas secara
sembarangan. Karena Java applet dapat membuka jendela browser yang
baru, maka jendela mempunyai logo Java dan teks identifikasi terhadap
jendela yang dibuka. Hal ini mencegah jendela pop-up menipu sebagai
permintaan keterangan username dan password.
Fase – fase Pemrograman JAVA
Langkah pertama dalam pembuatan sebuah program berbasis Java adalah
menuliskan kode program pada text editor. Contoh text editor yang dapat digunakan
antara lain : notepad, vi, emacs dan lain sebagainya. Kode program yang dibuat
kemudian tersimpan dalam sebuah berkas berekstensi .java.
Setelah membuat dan menyimpan kode program, kompilasi file yang berisi kode
program tersebut dengan menggunakan Java Compiler. Hasil dari kompilasi berupa
berkas bytecode dengan ekstensi .class.
Berkas yang mengandung bytecode tersebut kemudian akan dikonversikan oleh Java
Interpreter menjadi bahasa mesin sesuai dengan jenis dan platform yang digunakan.
Proses Tool Hasil
Menulis kode program Text editor Berkas berekstensi .java
Kompilasi program Java Compiler Berkas berekstensi .class
(Java Bytecodes)
Menjalankan program Java Interpreter Program Output

4:26 PM | 0 comments | Read More

Mengenali Lingkup Pemrograman Anda-Java

IDE adalah sebuah peralatan dalam pemrograman yang diintegrasikan ke dalam aplikasi
software yang mendukung pembangunan GUI, teks atau penulisan kode, compiler dan
debugger.
Tutorial ini menggunakan Ubuntu Dapper sebagai sistem operasinya. Sebelum
menggunakan tutorial ini, pastikan bahwa telah menginstal Java dan NetBeans dalam
sistem yang Anda gunakan. Untuk instruksi bagaimana cara menginstal Java dan
NetBeans, dapat dilihat pada Appendix A. Untuk versi Windows XP dalam bagian ini,
dapat dilihat pada Appendix B.
Sebelum membahas lebih terperinci, pada awalnya akan kita lihat program Java pertama
yang akan Anda tulis.
Program Java Pertama
public class Hello
{
/**
* My first java program
*/
public static void main(String[] args) {
//Menampilkan kata "Hello world" dilayar
System.out.println("Hello world!");
}
}
Sebelum menjelaskan apa arti dari program tersebut, cobalah untuk menulis program
ini di dalam file dan kemudian menjalankannya.
Menggunakan Text Editor dan Console
Dalam contoh ini, kita akan menggunakan text editor untuk mengedit program Java.
Anda juga akan membuka terminal window untuk mengkompilasi dan mengeksekusi
program Java Anda.
Langkah 1: Memulai Text Editor
Untuk memulai text editor di Linux , klik pada Applications->Accessories->Text Editor.
Langkah 2: Membuka Terminal
Untuk membuka terminal di Linux, klik pada Applications-> Accessories-> Terminal.
Langkah 3: Tulislah listing program Java Anda dalam text editor.
Langkah 4: Simpanlah program Java Anda
Program ini akan disimpan dalam file yang bernama ''Hello.java'', dan disimpan dalam
sebuah folder yang bernama MYJAVAPROGRAMS.
Untuk membuka Save dialog box, klik pada File menu yang terdapat pada menubar dan
kemudian klik save.
Setelah melakukan instruksi tersebut, dialog box akan tampil seperti gambar
Klik pada tombol browse, kemudian klik tombol Create Folder.
Nama folder baru, MYJAVAPROGRAMS. Sekarang, klik pada folder MYJAVAPROGRAMS
untuk mengetahui isi folder yang ada didalamnya. Setelah Anda klik pada folder
tersebut, Anda akan melihat gambar yang ditampilkan seperti berikut ini. Untuk saat ini
folder tersebut harus kosong sampai terbuatnya folder baru dan kita akan menyimpan
semuanya didalam folder tersebut.
Sekarang, dalam textbox Selection, ketiklah nama file dari program Anda, yaitu
''Hello.java'', kemudian klik pada tombol SAVE.
Sekarang Anda telah menyimpan file Anda, ingatlah cara bagaimana nama frame dapat
berubah dari ''Untitled Document 1 (modified) – gedit'' menjadi "Hello.java
(~/MYJAVAPROGRAMS) – gedit". Jika Anda ingin melakukan perubahan pada file Anda,
Anda hanya perlu mengeditnya, kemudian menyimpannya kembali dengan mengklik
pada File->Save.
Langkah 5: Mengkompilasi program Anda
Langkah berikut ini adalah mengkompilasi program Anda. Masuklah ke Terminal Window
yang telah kita buka sebelumnya.
Ketika Anda membuka terminal window, terminal tersebut menampilkan jendela yang
disebut sebagai home folder Anda. Untuk melihat isi dari folder tersebut, ketik ls dan
kemudian tekan ENTER. Apa yang akan Anda temukan adalah daftar file-file dan folder
di dalamnya.
Disinilah Anda dapat melihat folder dengan nama "MYJAVAPROGRAMS" yang telah kita
buat sebelumnya, dan merupakan tempat dimana kita menyimpan program Hello.java
kita. Kemudian masuklah ke dalam direktori tersebut.
Untuk masuk ke dalam sebuah direktori, ketiklah perintah : cd [directory name].
Perintah ''cd'' digunakan untuk merubah direktori. Dalam hal ini, nama dari direktori kita
adalah MYJAVAPROGRAM, maka Anda harus mengetik : cd MYJAVAPROGRAMS.
Setelah berada di dalam folder yang berisi program Java Anda, sudah saatnya untuk
memulai meng-compile program Java tersebut. Sebagai catatan, bahwa file yang Anda
maksud harus ada didalam folder yang Anda pilih. Periksalah dengan menjalankan
perintah ''ls'' lagi untuk melihat bahwa file Anda ada didalam folder tersebut.
Untuk mengkompilasi program Java, gunakanlah perintah : javac [filename]. Dalam
hal ini, Anda mengetikan perintah : javac Hello.Java.
Selama pengkompilasian, javac menambah file ke dalam disk yang disebut
[filename].class, atau dalam hal ini, Hello.class, yang merupakan kode sebenarnya.
Langkah 6 : Menjalakan Program
Selama proses pengkompilasian, javac menambah file baru kedalam disk yang disebut
[filename].class, dalam hal ini, Hello.class, yang merupakan kode sebenarnya saat
ini, dengan perkiraan tidak ada permasalahan pada saat proses compile (kita akan
menyelidiki dan membahas permasalahan yang ditemukan selama proses compile, pada
bagian berikutnya), berarti telah siap untuk menjalankan program Anda.
Untuk menjalankan program Java Anda, dengan mengetikkan perintah : java [filename
without the extension], maka dalam hal ini, Anda mengetikkan perintah : java Hello.
Sekarang Anda dapat melihat di layar bahwa Anda telah menjalankan program Java
pertama Anda, yang menampilkan pesan, ''Hello world!''.

4:20 PM | 0 comments | Read More

App Part 1: Creating controls at runtime

Wednesday, June 3, 2009 | 10:27 AM|

Example: app_one
I thought that since an example on creating controls on the fly, although usefull, would be quite pointless unless the application actually did something, so in this entry I will start the workings of a text editor and build upon it untill we reach a nearly useful program that supports opening, editing and saving text documents.

The first step, which this particular page covers will be simply creating the window and the EDIT control that will serve as the center of our program.

Starting with the skeleton code from the Simple Window application we add a #define as our control ID and the following two message handlers into our window procedure:


#define IDC_MAIN_EDIT 101 
    case WM_CREATE:     {         HFONT hfDefault;         HWND hEdit;          hEdit = CreateWindowEx(WS_EX_CLIENTEDGE, "EDIT", "",              WS_CHILD | WS_VISIBLE | WS_VSCROLL | WS_HSCROLL | ES_MULTILINE | ES_AUTOVSCROLL | ES_AUTOHSCROLL,              0, 0, 100, 100, hwnd, (HMENU)IDC_MAIN_EDIT, GetModuleHandle(NULL), NULL);         if(hEdit == NULL)             MessageBox(hwnd, "Could not create edit box.", "Error", MB_OK | MB_ICONERROR);          hfDefault = GetStockObject(DEFAULT_GUI_FONT);         SendMessage(hEdit, WM_SETFONT, (WPARAM)hfDefault, MAKELPARAM(FALSE, 0));     }     break;     case WM_SIZE:     {         HWND hEdit;         RECT rcClient;          GetClientRect(hwnd, &rcClient);          hEdit = GetDlgItem(hwnd, IDC_MAIN_EDIT);         SetWindowPos(hEdit, NULL, 0, 0, rcClient.right, rcClient.bottom, SWP_NOZORDER);     }     break; 

Creating controls

Creating controls, like creating any other window, is done through the CreateWindowEx() API. We pass in pre-registered class that we want, in this case the "EDIT" control class, and we get a standard edit control window. When using dialogs to create our controls, we are basically writing a list of controls to create so that then you call DialogBox() or CreateDialog() the system reads through the list of controls in the dialog resource and calls CreateWindowEx() for each one with the position and styles that were defined in the resource.
    hEdit = CreateWindowEx(WS_EX_CLIENTEDGE, "EDIT", "",          WS_CHILD | WS_VISIBLE | WS_VSCROLL | WS_HSCROLL | ES_MULTILINE | ES_AUTOVSCROLL | ES_AUTOHSCROLL,          0, 0, 100, 100, hwnd, (HMENU)IDC_MAIN_EDIT, GetModuleHandle(NULL), NULL);     if(hEdit == NULL)         MessageBox(hwnd, "Could not create edit box.", "Error", MB_OK | MB_ICONERROR); 
You can see that this call to CreateWindowEx() specifies quite a few styles, and it's not uncommon to have many more, especially for the Common Controls which have a hearty list of options. The first 4 WS_ styles should be fairly obvious, we are creating the control as a child of our window, we want it to be visible, and have vertical and horizontal scroll bars.

The 3 styles that are specific to EDIT controls (ES_MULTILINE | ES_AUTOVSCROLL | ES_AUTOHSCROLL) specify that the EDIT control should contain multiple lines of text, and scroll automatically as you type beyond the bottom and right hand side of the control respectively.

The regular window styles (WS_*) are listed here. And the extended windows styles (WS_EX_*) are explained under theCreateWindowEx() reference in MSDN, where you can also find links to the styles that are specific to each control (ES_* in our case of the edit control).

We have specified our window handle as the parent of the control, and assigned it an ID of IDC_MAIN_EDIT which we'll use later on to refer to the control just as you would if the control had been created on a dialog. The position and size parameters don't mean too much at the moment since we will be resizing the control dynamically in the WM_SIZE message so that it will always fit our window.

Sizing of dynamically created controls

Generally if your window is sizeable you'll want some code to resize or reposition the controls you created within it so that they are always layed out properly.
    GetClientRect(hwnd, &rcClient);      hEdit = GetDlgItem(hwnd, IDC_MAIN_EDIT);     SetWindowPos(hEdit, NULL, 0, 0, rcClient.right, rcClient.bottom, SWP_NOZORDER); 

Since we only have one control for now, the task is relatively simple. We use GetClientRect() to get the dimentions of the Client Area of the window, the big (up untill now) blank area that does not include the borders, menu or caption. This will fill in our RECTstructure with the value, the left and top values will always be 0, so you can usually just ignore them. The right and bottomvalues will give you the width and the hight of the client area.

Next we simply get a handle to our edit control using GetDlgItem() which works just as well on regular windows as it does on dialogs, and the call SetWindowPos() to move and size it to fill the entire client area. You can of course change the values you pass into SetWindowPos() to do something like only fill half of the window's height, leaving the bottom free to place other controls.

Creating other controls at runtime

I'm not going to give examples of dynamically creating the other controls like LISTBOX, BUTTON, etc... because it's basically the same and it gets kinda boring after a while :) If you follow the links into MSDN above, or look in your local Win32 API reference you will be able to find all of the information needed to create any of the other standard controls.

We'll be doing more of this with the common controls in the next couple of sections so you'll get more practice eventually.



10:27 AM | 0 comments | Read More

A Simple Window

Sometimes people come on IRC and ask "How do I make a window?"...Well it's not entirely that simple I'm afraid. It's not difficult once you know what you're doing but there are quite a few things you need to do to get a window to show up; And they're more than can be simply explained over a chat room, or a quick note.
I always liked to do things first and learn them later...so here is the code to a simple window which will be explained shortly.


#include   const char g_szClassName[] = "myWindowClass";  // Step 4: the Window Procedure LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {     switch(msg)     {         case WM_CLOSE:             DestroyWindow(hwnd);         break;         case WM_DESTROY:             PostQuitMessage(0);         break;         default:             return DefWindowProc(hwnd, msg, wParam, lParam);     }     return 0; }  int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,     LPSTR lpCmdLine, int nCmdShow) {     WNDCLASSEX wc;     HWND hwnd;     MSG Msg;      //Step 1: Registering the Window Class     wc.cbSize        = sizeof(WNDCLASSEX);     wc.style         = 0;     wc.lpfnWndProc   = WndProc;     wc.cbClsExtra    = 0;     wc.cbWndExtra    = 0;     wc.hInstance     = hInstance;     wc.hIcon         = LoadIcon(NULL, IDI_APPLICATION);     wc.hCursor       = LoadCursor(NULL, IDC_ARROW);     wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);     wc.lpszMenuName  = NULL;     wc.lpszClassName = g_szClassName;     wc.hIconSm       = LoadIcon(NULL, IDI_APPLICATION);      if(!RegisterClassEx(&wc))     {         MessageBox(NULL, "Window Registration Failed!", "Error!",             MB_ICONEXCLAMATION | MB_OK);         return 0;     }      // Step 2: Creating the Window     hwnd = CreateWindowEx(         WS_EX_CLIENTEDGE,         g_szClassName,         "The title of my window",         WS_OVERLAPPEDWINDOW,         CW_USEDEFAULT, CW_USEDEFAULT, 240, 120,         NULL, NULL, hInstance, NULL);      if(hwnd == NULL)     {         MessageBox(NULL, "Window Creation Failed!", "Error!",             MB_ICONEXCLAMATION | MB_OK);         return 0;     }      ShowWindow(hwnd, nCmdShow);     UpdateWindow(hwnd);      // Step 3: The Message Loop     while(GetMessage(&Msg, NULL, 0, 0) > 0)     {         TranslateMessage(&Msg);         DispatchMessage(&Msg);     }     return Msg.wParam; } 
For most part this is the simplest windows program you can write that actually creates a functional window, a mere 70 or so lines. If you got the first example to compile then this one should work with no problems.

Step 1: Registering the Window Class

Window Class stores information about a type of window, including it's Window Procedure which controls the window, the small and large icons for the window, and the background color. This way, you can register a class once, and create as many windows as you want from it, without having to specify all those attributes over and over. Most of the attributes you set in the window class can be changed on a per-window basis if desired.

A Window Class has NOTHING to do with C++ classes.

const char g_szClassName[] = "myWindowClass"; 
The variable above stores the name of our window class, we will use it shortly to register our window class with the system.
    WNDCLASSEX wc; 
    wc.cbSize        = sizeof(WNDCLASSEX);     wc.style         = 0;     wc.lpfnWndProc   = WndProc;     wc.cbClsExtra    = 0;     wc.cbWndExtra    = 0;     wc.hInstance     = hInstance;     wc.hIcon         = LoadIcon(NULL, IDI_APPLICATION);     wc.hCursor       = LoadCursor(NULL, IDC_ARROW);     wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);     wc.lpszMenuName  = NULL;     wc.lpszClassName = g_szClassName;     wc.hIconSm       = LoadIcon(NULL, IDI_APPLICATION);      if(!RegisterClassEx(&wc))     {         MessageBox(NULL, "Window Registration Failed!", "Error!",             MB_ICONEXCLAMATION | MB_OK);         return 0;     } 

This is the code we use in WinMain() to register our window class. We fill out the members of a WNDCLASSEXstructure and call RegisterClassEx().

The members of the struct affect the window class as follows:

cbSize
The size of the structure.
style
Class Styles (CS_*), not to be confused with Window Styles (WS_*) This can usually be set to 0.
lpfnWndProc
Pointer to the window procedure for this window class.
cbClsExtra
Amount of extra data allocated for this class in memory. Usually 0.
cbWndExtra
Amount of extra data allocated in memory per window of this type. Usually 0.
hInstance
Handle to application instance (that we got in the first parameter of WinMain()).
hIcon
Large (usually 32x32) icon shown when the user presses Alt+Tab.
hCursor
Cursor that will be displayed over our window.
hbrBackground
Background Brush to set the color of our window.
lpszMenuName
Name of a menu resource to use for the windows with this class.
lpszClassName
Name to identify the class with.
hIconSm
Small (usually 16x16) icon to show in the taskbar and in the top left corner of the window.
Don't worry if that doesn't make much sense to you yet, the various parts that count will be explained more later. Another thing to remember is to not try and remember this stuff. I rarely (never) memorize structs, or function parameters, this is a waste of effort and, more importantly, time. If you know the functions you need to call then it is a matter of seconds to look up the exact parameters in your help files. If you don't have help files, get them. You are lost without. Eventually you will come to know the parameters to the functions you use most.

We then call RegisterClassEx() and check for failure, if it fails we pop up a message which says so and abort the program by returning from the WinMain() function.

Step 2: Creating the Window

Once the class is registered, we can create a window with it. You should look up the paramters forCreateWindowEx() (as you should ALWAYS do when using a new API call), but I'll explain them briefly here.

    HWND hwnd; 
    hwnd = CreateWindowEx(         WS_EX_CLIENTEDGE,         g_szClassName,         "The title of my window",         WS_OVERLAPPEDWINDOW,         CW_USEDEFAULT, CW_USEDEFAULT, 240, 120,         NULL, NULL, hInstance, NULL); 

The first parameter (WS_EX_CLIENTEDGE) is the extended windows style, in this case I have set it to give it a sunken inner border around the window. Set it to 0 if you'd like to see the difference. Also play with other values to see what they do.

Next we have the class name (g_szClassName), this tells the system what kind of window to create. Since we want to create a window from the class we just registered, we use the name of that class. After that we specify our window name or title which is the text that will be displayed in the Caption, or Title Bar on our window.

The parameter we have as WS_OVERLAPPEDWINDOW is the Window Style parameter. There are quite a few of these and you should look them up and experiment to find out what they do. These will be covered more later.

The next four parameters (CW_USEDEFAULT, CW_USEDEFAULT, 320, 240) are the X and Y co-ordinates for the top left corner of your window, and the width and height of the window. I've set the X and Y values to CW_USEDEFAULTto let windows choose where on the screen to put the window. Remeber that the left of the screen is an X value of zero and it increases to the right; The top of the screen is a Y value of zero which increases towards the bottom. The units are pixels, which is the smallest unit a screen can display at a given resolution.

Next (NULL, NULL, g_hInst, NULL) we have the Parent Window handle, the menu handle, the application instance handle, and a pointer to window creation data. In windows, the windows on your screen are arranged in a heirarchy of parent and child windows. When you see a button on a window, the button is the Child and it is contained within the window that is it's Parent. In this example, the parent handle is NULL because we have no parent, this is our main or Top Level window. The menu is NULL for now since we don't have one yet. The instance handle is set to the value that is passed in as the first parameter to WinMain(). The creation data (which I almost never use) that can be used to send additional data to the window that is being created is also NULL.

If you're wondering what this magic NULL is, it's simply defined as 0 (zero). Actually, in C it's defined as((void*)0), since it's intended for use with pointers. Therefore you will possibly get warnings if you use NULL for integer values, depending on your compiler and the warning level settings. You can choose to ignore the warnings, or just use 0 instead.

Number one cause of people not knowing what the heck is wrong with their programs is probably that they didn't check the return values of their calls to see if they failed or not. CreateWindow() will fail at some point even if you're an experianced coder, simply because there are lots of mistakes that are easy to make. Untill you learn how to quickly identify those mistakes, at least give yourself the chance of figuring out where things go wrong, andAlways check return values!

    if(hwnd == NULL)     {         MessageBox(NULL, "Window Creation Failed!", "Error!",             MB_ICONEXCLAMATION | MB_OK);         return 0;     } 

After we've created the window and checked to make sure we have a valid handle we show the window, using the last parameter in WinMain() and then update it to ensure that it has properly redrawn itself on the screen.

   ShowWindow(hwnd, nCmdShow);    UpdateWindow(hwnd); 

The nCmdShow parameter is optional, you could simply pass in SW_SHOWNORMAL all the time and be done with it. However using the parameter passed into WinMain() gives whoever is running your program to specify whether or not they want your window to start off visible, maximized, minimized, etc... You will find options for these in the properties of windows shortcuts, and this parameter is how the choice is carried out.

Step 3: The Message Loop

This is the heart of the whole program, pretty much everything that your program does passes through this point of control.

    while(GetMessage(&Msg, NULL, 0, 0) > 0)     {         TranslateMessage(&Msg);         DispatchMessage(&Msg);     }     return Msg.wParam; 

GetMessage() gets a message from your application's message queue. Any time the user moves the mouse, types on the keyboard, clicks on your window's menu, or does any number of other things, messages are generated by the system and entered into your program's message queue. By calling GetMessage() you are requesting the next available message to be removed from the queue and returned to you for processing. If there is no message,GetMessage() Blocks. If you are unfamiliar with the term, it means that it waits untill there is a message, and then returns it to you.

TranslateMessage() does some additional processing on keyboard events like generating WM_CHAR messages to go along with WM_KEYDOWN messages. Finally DispatchMessage() sends the message out to the window that the message was sent to. This could be our main window or it could be another one, or a control, and in some cases a window that was created behind the scenes by the sytem or another program. This isn't something you need to worry about because all we are concerned with is that we get the message and send it out, the system takes care of the rest making sure it gets to the proper window.

Step 4: the Window Procedure

If the message loop is the heart of the program, the window procedure is the brain. This is where all the messages that are sent to our window get processed.
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {     switch(msg)     {         case WM_CLOSE:             DestroyWindow(hwnd);         break;         case WM_DESTROY:             PostQuitMessage(0);         break;         default:             return DefWindowProc(hwnd, msg, wParam, lParam);     }     return 0; } 

The window procedure is called for each message, the HWND parameter is the handle of your window, the one that the message applies to. This is important since you might have two or more windows of the same class and they will use the same window procedure (WndProc()). The difference is that the parameter hwnd will be different depending on which window it is. For example when we get the WM_CLOSE message we destroy the window. Since we use the window handle that we received as the first paramter, any other windows will not be affected, only the one that the message was intended for.

WM_CLOSE is sent when the user presses the Close Button [x] or types Alt-F4. This will cause the window to be destroyed by default, but I like to handle it explicitly, since this is the perfect spot to do cleanup checks, or ask the user to save files etc. before exiting the program.

When we call DestroyWindow() the system sends the WM_DESTROY message to the window getting destroyed, in this case it's our window, and then destroys any remaining child windows before finally removing our window from the system. Since this is the only window in our program, we are all done and we want the program to exit, so we call PostQuitMessage(). This posts the WM_QUIT message to the message loop. We never receive this message, because it causes GetMessage() to return FALSE, and as you'll see in our message loop code, when that happens we stop processing messages and return the final result code, the wParam of WM_QUIT which happens to be the value we passed into PostQuitMessage(). The return value is only really useful if your program is designed to be called by another program and you want to return a specific value.

Step 5: There is no Step 5

Phew. Well that's it! If I haven't explained stuff clearly enough yet, just hang in there and hopefully things will become more clear as we get into more usefull programs.



10:23 AM | 0 comments | Read More

Getting Started

What this tutorial is all about

This tutorial is intended to present to you the basics (and common extras) of writing programs using the Win32 API. The language used is C, most C++ compilers will compile it as well. As a matter of fact, most of the information is applicable to any language that can access the API, inlcuding Java, Assembly and Visual Basic. I will not however present any code relating to these languages and you're on your own in that regard, but several people have previously used this document in said languages with quite a bit of success.
This tutorial will not teach you the C language, nor will it tell you how to run your perticular compiler (Borland C++, Visual C++, LCC-Win32, etc...) I will however take a few moments in the appendix to provide some notes on using the compilers I have knowledge of.If you don't know what a macro or a typedef are, or how a switch() statement works, then turn back now and read a good book or tutorial on the C language first.

Important notes

Sometimes throughout the text I will indicate certain things are IMPORANT to read. Because they screw up so many people, if you don't read it, you'll likely get caught too. The first one is this:
The source provided in the example ZIP file is not optional! I don't include all the code in the text itself, only that which is relevant to whatever I'm currently discussing. In order to see how this code fits in with the rest of the program, you must take a look at the source provided in the ZIP file.

And here's the second one:

Read the whole thing! If you have a question during one section of the tutorial just have a little patience and it might just be answered later on. If you just can't stand the thought of not knowing, at least skim or search (yes computers can do that) the rest of the document before asking the nice folks on IRC or by email.

Another thing to remember is that a question you might have about subject A might end up being answered in a discussion of B or C, or maybe L. So just look around a little.

Ok I think that's all the ranting I have to do for the moment, lets try some actual code.

The simplest Win32 program

If you are a complete beginner lets make sure you are capable of compiling a basic windows application. Slap the following code into your compiler and if all goes well you should get one of the lamest programs ever written.
Remember to compile this as C, not C++. It probably doesn't matter, but since all the code here is C only, it makes sense to start off on the right track. In most cases, all this requires if you add your code to a .c file instead of a .cpp file. If all of this hurts your head, just call the file test.c and be done with it.

#include

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int nCmdShow)
{
MessageBox(NULL, "Goodbye, cruel world!", "Note", MB_OK);
return 0;
}
If that doesn't work, your first step is to read whatever errors you get and if you don't understand them, look them up in the help or whatever documents accompany your compiler. Make sure you have specified a Win32 GUI (NOT "Console") project/makefile/target, whatever applies to your compiler. Unfortunately I can't help much with this part either, as errors and how to fix them vary from compiler to compiler (and person to person).

You may get some warnings about you not using the parameters supplied to WinMain(). This is OK. Now that we've established you can in fact compile a program, lets go through that little bit of code....

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int nCmdShow)
WinMain() is windows equivalent of main() from DOS or UNIX. This is where your program starts execution. The parameters are as follows:
HINSTANCE hInstance
Handle to the programs executable module (the .exe file in memory)
HINSTANCE hPrevInstance
Always NULL for Win32 programs.
LPSTR lpCmdLine
The command line arguments as a single string. NOT including the program name.
int nCmdShow
An integer value which may be passed to ShowWindow(). We'll get to this later.
hInstance is used for things like loading resources and any other task which is performed on a per-module basis. A module is either the EXE or a DLL loaded into your program. For most (if not all) of this tutorial, there will only be one module to worry about, the EXE.

hPrevInstance used to be the handle to the previously run instance of your program (if any) in Win16. This no longer applies. In Win32 you ignore this parameter.

Calling Conventions

WINAPI specifies the calling convention and is defined as _stdcall. If you don't know what this means, don't worry about it as it will not really affect us for the scope of this tutorial. Just remember that it's needed here.

Win32 Data Types

You will find that many of the normal keywords or types have windows specific definitions, UINT for unsigned int, LPSTR for char* etc... Which you choose is really up to you. If you are more comfortable using char* instead of LPSTR, feel free to do so. Just make sure that you know what a type is before you substitute something else.
Just remember a few things and they will be easy to interpret. An LP prefix stands for Long Pointer. In Win32 the Long part is obsolete so don't worry about it. And if you don't know what a pointer is, you can either 1) Go find a book or tutorial on C, or 2) just go ahead anyway and screw up a lot. I'd really recommend #1, but most people go with #2 (I would :). But don't say I didn't warn you.

Next thing is a C following a LP indicates a const pointer. LPCSTR indicates a pointer to a const string, one that can not or will not be modified. LPSTR on the other hand is not const and may be changed.

You might also see a T mixed in there. Don't worry about this for now, unless you are intentionally working with Unicode, it means nothing.

10:21 AM | 0 comments | Read More