关于前台窗口的解决方法
最近做了一个小程序,要从自己编写的小程序切换到autoCAD窗口,当然用alt+tab也可以切换,现在想自动切换,以前用vb的时候知道怎么做,现在用vb.net了。到网上搜了好久也没有看到好方法,呵呵,就把以前的vb代码升级了一下,大家看着用。。有好方法的告诉我一声。。代码示例:要求新建一个窗体应用程序项目,在form1里面添加一个Button1按钮,复制下面代码,运行点击button1,切换到autocad窗口,在cad窗体上面选择一点,然后返回到form窗口。
Public Class Form1
Private Declare Function GetWindowThreadProcessId Lib "user32" (ByVal hWnd As Integer, ByRef lpdwProcessId As Integer) As Integer
Private Declare Function AttachThreadInput Lib "user32" (ByVal idAttach As Integer, ByVal idAttachTo As Integer, ByVal fAttach As Integer) As Integer
Private Declare Function GetForegroundWindow Lib "user32" () As Integer
Private Declare Function SetForegroundWindow Lib "user32" (ByVal hWnd As Integer) As Integer
Private Declare Function IsIconic Lib "user32" (ByVal hWnd As Integer) As Integer
Private Declare Function ShowWindow Lib "user32" (ByVal hWnd As Integer, ByVal nCmdShow As Integer) As Integer
Private Const SW_SHOW As Short = 5
Private Const SW_RESTORE As Short = 9
Public Function ForceForegroundWindow(ByVal hWnd As Integer) As Boolean
Dim ThreadID1 As Integer ' 线程ID
Dim ThreadID2 As Integer ' 线程ID
Dim nRet As Integer
'如果指定的窗体已经在前台,不做任何操作
If hWnd = GetForegroundWindow() Then
ForceForegroundWindow = True
Else
' 首先获得指定窗体相关的线程和当前前台窗口所在的线程
ThreadID1 = GetWindowThreadProcessId(GetForegroundWindow, 0)
ThreadID2 = GetWindowThreadProcessId(hWnd, 0)
' 通过共享输入状态,两个线程分享当前窗口
If ThreadID1 <> ThreadID2 Then
Call AttachThreadInput(ThreadID1, ThreadID2, True)
nRet = SetForegroundWindow(hWnd)
Call AttachThreadInput(ThreadID1, ThreadID2, False)
Else
nRet = SetForegroundWindow(hWnd)
End If
'恢复和重画
If IsIconic(hWnd) Then
Call ShowWindow(hWnd, SW_RESTORE)
Else
Call ShowWindow(hWnd, SW_SHOW)
End If
'精确地返回函数执行结果
ForceForegroundWindow = CBool(nRet)
End If
End Function
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim myAcadApp As Object
myAcadApp = GetObject(, "Autocad.Application") '获得autocad程序
' myAcadApp = GetObject(, "Excel.Application")'如果想切换到excel窗口,用这句代码
ForceForegroundWindow(myAcadApp.hWnd)
myAcadApp.ActiveDocument.Utility.GetPoint(, "选择一点:")
ForceForegroundWindow(Me.Handle)
End Sub
End Class
.net2008源码
呃,都窗口句柄了。
你写的程序是独立于AutoCAD的吗?还是使用插件的方式?要是是插件的话,就容易多了 cdinten 发表于 2011-8-19 23:44 static/image/common/back.gif
呃,都窗口句柄了。
你写的程序是独立于AutoCAD的吗?还是使用插件的方式?要是是插件的话,就容易多了
程序是独立的,输出到cad只是里面的一个功能。。 AppActivate(myAcadApp.Caption) 河伯 发表于 2011-8-20 11:48 static/image/common/back.gif
AppActivate(myAcadApp.Caption)
这个好像不会切换,只是任务栏了autocad变成亮色了。。。 这是共享线程的方法,在张帆斑竹的书中有介绍
页:
[1]