這篇文章不是Windows Mobile的,而是Win32的。這篇文章主要介紹一下C#下如何調用Windows API函數,這裡也想說一下,Windows Mobile編程不能把眼光只局限於手機,手機與PC端相結合的程式也是很有挑戰力、很有市場的。所以,這也是我寫這篇文章的原因之一。
做Delphi的時候,實現表單透明很簡單,因為Delphi對Windows API的封裝很好。不只對API函數封裝的到位,對API函數所用到的參數封裝的也很好。而.net沒有對API函數進行封裝,對API函數的參數就更沒有封裝了。調用API函數只能用Invoke的方式,參數也需要我們自己進行相關定義。
DesktopWinAPI.cs類檔案,Invoke了表單透明所需要的API函數:
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace DeviceAnywhereDesktop
{
class DesktopWinAPI
{
[DllImport("user32.dll")]
public extern static IntPtr GetDesktopWindow();
[DllImport("user32.dll")]
public extern static bool SetLayeredWindowAttributes(IntPtr hwnd, uint crKey, byte bAlpha, uint dwFlags);
public static uint LWA_COLORKEY = 0x00000001;
public static uint LWA_ALPHA = 0x00000002;
[DllImport("user32.dll")]
public extern static uint SetWindowLong(IntPtr hwnd, int nIndex, uint dwNewLong);
[DllImport("user32.dll")]
public extern static uint GetWindowLong(IntPtr hwnd, int nIndex);
public enum WindowStyle : int
{
GWL_EXSTYLE = -20
}
public enum ExWindowStyle : uint
{
WS_EX_LAYERED = 0x00080000
}
}
}
DeviceForm.cs單元是API函數的調用方式:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace DeviceAnywhereDesktop
{
public partial class DeviceForm : Form
{
public DeviceForm()
{
InitializeComponent();
}
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
cp.Parent = DesktopWinAPI.GetDesktopWindow();
cp.ExStyle = 0x00000080 | 0x00000008;//WS_EX_TOOLWINDOW | WS_EX_TOPMOST
return cp;
}
}
private void SetWindowTransparent(byte bAlpha)
{
try
{
DesktopWinAPI.SetWindowLong(this.Handle, (int)DesktopWinAPI.WindowStyle.GWL_EXSTYLE,
DesktopWinAPI.GetWindowLong(this.Handle, (int)DesktopWinAPI.WindowStyle.GWL_EXSTYLE) | (uint)DesktopWinAPI.ExWindowStyle.WS_EX_LAYERED);
DesktopWinAPI.SetLayeredWindowAttributes(this.Handle, 0, bAlpha, DesktopWinAPI.LWA_COLORKEY | DesktopWinAPI.LWA_ALPHA);
}
catch
{
}
}
private void DeviceForm_Load(object sender, EventArgs e)
{
this.SetWindowTransparent(100);
}
}
}