Private Const SW_MINIMIZE As Integer = 6
Protected Overrides Sub OnGotFocus(ByVal e As EventArgs)
Dim hwnd As IntPtr = FindWindow(Nothing, Me.Text)
ShowWindow(hwnd, SW_MINIMIZE)
MyBase.OnGotFocus(e)
End Sub 'OnGotFocus
6.7. 在微软.net精简框架上调用系统函数时,如何装配数据类型?
见本问答的 "6.1. 如何调用本地写的DLL中的函数? " 章节。
6.8. 如何得到一个窗体或控件的句柄 (HWND) ?
其实有一些使用调用本地代码的方法可以获得控件的句柄HWND。下面列出其中两种,一种使用GetCapture,另一个使用FindWindow。 //C#
[DllImport("coredll.dll"]
public static extern IntPtr GetCapture();
[DllImport("coredll.dll")]
public static extern IntPtr FindWindow(String lpClassName, String lpWindowName);
this.Text = "FindMe";
IntPtr hwnd1 = FindWindow(null, "FindMe");
this.Capture = true;
IntPtr hwnd2 = GetCapture();
this.Capture = false;
'VB
<DllImport("coredll.dll", SetLastError:=True)> _
Public Shared Function GetCapture() As IntPtr
End Function
<DllImport("coredll.dll", SetLastError:=True)> _
Public Shared Function FindWindow(ByVal lpClassName As String, ByVal lpWindowName As String) As IntPtr
End Function
Me.Text = "FindMe"
Dim deskWin As IntPtr = FindWindow(Nothing, "FindMe")
Me.Capture = True
Dim hwnd As IntPtr = GetCapture()
Me.Capture = False
6.9. 如何使用性能计数器功能?
使用QueryPerformanceFrequency函数和QueryPerformanceCounter函数可以建立精确的计时程序。 这些功能是和设备提供商相关的,如果他们不能执行,那么只能和GetTickCount功能得到一样的结果。如果能执行这些函数,就能保证计时器最准确的运行,比GetTickCounter或Environment.TickCount准确得多。TickCount其实是调用GetTickCounter的。
如果性能计数器是GetTickCount的一个实例,QueryPerformanceFrequency将把1000作为计时频率。如果这些函数不能执行,将得到返回值为0。以下代码演示了如何使用这些函数。//C#
[DllImport("CoreDll.dll")]
public static extern int QueryPerformanceFrequency(ref Int64 lpFrequency);
[DllImport("CoreDll.dll")]
public static extern int QueryPerformanceCounter(ref Int64 lpPerformanceCount);
private void TestTimer()
{
System.Int64 freq = 0;
if (QueryPerformanceFrequency(ref freq) != 0)
{
System.Int64 count1 = 0;
System.Int64 count2 = 0;
if (QueryPerformanceCounter(ref count1) != 0)
{
System.Threading.Thread.Sleep(1200);
QueryPerformanceCounter(ref count2);
System.Int64 time_ms = (count2 - count1) * 1000 / freq;
}
}
}
'VB
<DllImport("CoreDll.dll")> _
Public Shared Function QueryPerformanceFrequency(ByRef lpFrequency As Int64) As Integer
End Function
<DllImport("coredll.dll")> _
Public Shared Function QueryPerformanceCounter(ByRef lpPerformanceCount As Int64) As Integer
End Function
Private Sub TestTimer()
Dim freq As System.Int64 = 0
If QueryPerformanceFrequency(freq) <> 0 Then
Dim count1 As System.Int64 = 0
Dim count2 As System.Int64 = 0
If QueryPerformanceCounter(count1) <> 0 Then
System.Threading.Thread.Sleep(1200)
QueryPerformanceCounter(count2)
Dim time_ms As System.Int64 = (count2 - count1) * 1000 / freq
End If
End If
End Sub 'TestTimer