Форум программистов, компьютерный форум, киберфорум
Visual Basic
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.57/7: Рейтинг темы: голосов - 7, средняя оценка - 4.57
7 / 7 / 0
Регистрация: 10.07.2015
Сообщений: 69

How can I get the handle in the virtual desktop

02.04.2020, 15:46. Показов 1678. Ответов 16
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
I created a new desktop and ran the calculator program in the new desktop. Now I want to get a handle to the calculator program ...

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Private Sub Form_Load()
    g_hDesktopThreadOld = GetThreadDesktop(App.ThreadID)  '
    RegisterHotKey Me.hwnd, 1, MOD_CONTROL, Asc("Q")  '
    RegisterHotKey Me.hwnd, 2, MOD_CONTROL, Asc("W")  '
    g_hDesktopNameNew = "MyNewDesktop"
    g_hDesktopNew = OpenDesktop(g_hDesktopNameNew, 0, False, DESKTOP_ALL)   '
   
    If g_hDesktopNew = 0 Then
        g_hDesktopNew = CreateDesktop(g_hDesktopNameNew, vbNullString, ByVal 0&, 0, MAXIMUM_ALLOWED, ByVal 0&)  '
    End If
 
    lpOldWinProc = SetWindowLong(Me.hwnd, GWL_WNDPROC, AddressOf myWindowProc)  '
    
End Sub
Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
Private Sub Command2_Click()
    StartMyExplore Text1.Text   'calc.exe
    
    Dim pTd     As Long
    Dim hThread As Long
    
    threadData.NotifyWnd = Text1.hwnd
    threadData.FindPath = SysAllocString(ByVal StrPtr("CalcFrame"))
    Sleep 3000
    hThread = vbCreateThread(0, 0, AddressOf Thread1, VarPtr(threadData), 0, 0)
    
End Sub
i used the trick modMultiThreading.bas to creat a new thread to Switch new Desktop

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
Public Sub Thread1(ByRef param As threadData)
 
    Dim mhwnd As Long, n As Long
    
    Call SetThreadDesktop(g_hDesktopNew)
    SwitchDesktop g_hDesktopNew
    Do
        mhwnd = FindWindow(param.FindPath, vbNullString)
        n = n + 1
        Sleep 1000
        DoEvents
 
        If n > 8 Or mhwnd <> 0 Then
            Exit Do
        End If
    Loop
 
    If mhwnd <> 0 Then
    
        SendMessageByString& param.NotifyWnd, WM_SETTEXT, 0, mhwnd
    
    Else
        SendMessageByString& param.NotifyWnd, WM_SETTEXT, 0, "error,cant find hwnd"
    End If
    
    Sleep 2000
    Call SetThreadDesktop(g_hDesktopThreadOld)
    SwitchDesktop g_hDesktopThreadOld
End Sub
Вложения
Тип файла: zip creatdesktop.zip (9.4 Кб, 5 просмотров)
0
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
02.04.2020, 15:46
Ответы с готовыми решениями:

Как выбрать окно, если его handle не совпадает с handle процесса?
Добрый день! Задача на первый взгляд довольно простая: выбрать окно программы, переместить его в определённую часть экрана и нажать на...

Что означает выражение HANDLE hWritePipe = (HANDLE)atoi(argv[1]);
К тому же у меня нет 1-го. только нулевой

desktop-amd64 или desktop-i368 на AMD
Какой дистриб лучше поставить на след проц??? проц на картинке. Непойму его разрядность, 32 или 64? Ос стоит х32!

16
7 / 7 / 0
Регистрация: 10.07.2015
Сообщений: 69
03.04.2020, 06:48  [ТС]
Modify attachment

@ help me?
Вложения
Тип файла: zip creatdesktop1.zip (10.3 Кб, 13 просмотров)
0
Модератор
10048 / 3894 / 883
Регистрация: 22.02.2013
Сообщений: 5,847
Записей в блоге: 79
03.04.2020, 09:22
You should call this function before CoInitialize because it creates a hidden window. Try to call SetThreadDesktop after CreateExprSrvObj.
CreateProcess has the STARTUPINFO parameter where you can specify a desktop.
0
7 / 7 / 0
Регистрация: 10.07.2015
Сообщений: 69
03.04.2020, 14:54  [ТС]
thanks !
but I don't know how to do. can you give me a demo. or some code?
0
7 / 7 / 0
Регистрация: 10.07.2015
Сообщений: 69
05.04.2020, 06:06  [ТС]
no body can help.

@.the trick thank you. I hope you can help me
0
Модератор
10048 / 3894 / 883
Регистрация: 22.02.2013
Сообщений: 5,847
Записей в блоге: 79
05.04.2020, 08:30
I'll help you later.
0
sleep
 Аватар для I can
4926 / 4576 / 840
Регистрация: 13.04.2015
Сообщений: 9,727
05.04.2020, 08:46
xxdoc, а на англоязычных форумах вам никто не может помочь ? Или за своего не признают ?
0
7 / 7 / 0
Регистрация: 10.07.2015
Сообщений: 69
05.04.2020, 12:17  [ТС]
I know that there are very few people who use vb now. I am also an amateur. I can not solve it, ...Can use Google Translate to communicate.
0
sleep
 Аватар для I can
4926 / 4576 / 840
Регистрация: 13.04.2015
Сообщений: 9,727
05.04.2020, 13:21
Цитата Сообщение от xxdoc Посмотреть сообщение
Can use Google Translate to communicate.
Я и без гугла всё хорошо понимаю. Не понимаю только одного, если английский для вас неродной(что заметно), то почему не переводить сразу на русский ? Из политических соображений ?
0
7 / 7 / 0
Регистрация: 10.07.2015
Сообщений: 69
05.04.2020, 13:41  [ТС]
If translated into Russian, I can't understand it myself.
0
05.04.2020, 13:58

Не по теме:

Китаец. Лучше пусть на английском пишет! :) Тем более, что правилами разрешено.

0
7 / 7 / 0
Регистрация: 10.07.2015
Сообщений: 69
08.04.2020, 02:29  [ТС]
i waiting good message from the trick!
0
7 / 7 / 0
Регистрация: 10.07.2015
Сообщений: 69
11.04.2020, 13:52  [ТС]
dear the trick ,Do you have time to solve this problem.I know it is impolite.
0
Модератор
10048 / 3894 / 883
Регистрация: 22.02.2013
Сообщений: 5,847
Записей в блоге: 79
11.04.2020, 22:35
xxdoc, when you create a process you should specify your desktop name:
Visual Basic
1
sui.lpDesktop = StrPtr(g_hDesktopNameNew)
You can't use hWnd to messaging across desktops so you need to switch between threads which belong to different desktops. I've made the example which uses the new version of the threading module with the small modification which allows to switch to a new desktop before any window was created.
Don't try to run it in the IDE because it works only in the compiled executable. That's because it uses APC and desktop switching. After you create a process in the new desktop you can get the window handle of a top-level window belonged to the process. You can change its caption as well.

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
Option Explicit
                            
Private m_hCurProcess   As Long
Private m_hDeskThread   As Long
Private m_tControlData  As tUserThreadData
 
Private Sub cmdGetMainHandle_Click()
    txtHandle.Text = Hex$(GetHandleOfTopWindow(m_hDeskThread, m_hCurProcess))
End Sub
 
Private Sub cmdRun_Click()
 
    If m_hCurProcess Then
        MsgBox "Already running", vbCritical
        Exit Sub
    End If
    
    m_hCurProcess = RunProcess(txtPath.Text)
    If m_hCurProcess = 0 Then
        MsgBox "Unable to run process", vbCritical
        Exit Sub
    End If
    
    m_tControlData.hEvent = CreateEvent(ByVal 0&, 1, 0, 0)
    
    m_hDeskThread = vbCreateThread(0, 0, AddressOf ThreadProc, VarPtr(m_tControlData), 0, 0)
    
    If m_hDeskThread = 0 Then
        MsgBox "Unable to create thread", vbCritical
        Exit Sub
    End If
    
    cmdRun.Enabled = False
    cmdGetMainHandle.Enabled = True
    cmdSetCaption.Enabled = True
    
End Sub
 
Private Sub cmdSetCaption_Click()
    
    If SetTopWindowCaption(m_hDeskThread, m_hCurProcess, txtHandle.Text) = 0 Then
        MsgBox "Unable to set caption", vbCritical
    End If
    
End Sub
 
Private Sub Form_Load()
        
    Me.Caption = Me.Caption & " [" & Hex$(Me.hWnd) & "]"
        
    If Not modMultiThreading.Initialize() Then
        MsgBox "Unable to initialize multithreading", vbCritical
        Exit Sub
    End If
    
    If RegisterHotKey(Me.hWnd, 1, MOD_CONTROL, Asc("W")) = 0 Then
        MsgBox "Unable to register hotkey", vbCritical
        Exit Sub
    End If
    
    If SetWindowSubclass(Me.hWnd, AddressOf SubclassWndProc, 1, ByVal 0&) = 0 Then
        MsgBox "Unable to subclass", vbCritical
        Exit Sub
    End If
    
    If Not InitDesktop() Then
        MsgBox "Unable to init desktop", vbCritical
        Exit Sub
    End If
    
    cmdRun.Enabled = True
    
End Sub
 
Private Sub Form_Unload(Cancel As Integer)
    
    If m_hCurProcess Then
        If Not CloseProcess(m_hDeskThread, m_hCurProcess) Then
            AbnormalTermination m_hCurProcess
        End If
    End If
    
    ' // End thread
    If m_hDeskThread Then
        SetEvent m_tControlData.hEvent
        WaitForSingleObjectEx m_hDeskThread, INFINITE, 0
    End If
    
    CloseHandle m_tControlData.hEvent
    CloseHandle m_hDeskThread
    
    SwitchToMainDesktop
    RemoveWindowSubclass Me.hWnd, AddressOf SubclassWndProc, 1
    UnregisterHotKey Me.hWnd, 1
    DestroyDesktop
    modMultiThreading.Uninitialize
    
End Sub
Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
Option Explicit
 
Public Const DESKTOP_NAME        As String = "MyNewDesktop"
Public Const MOD_CONTROL         As Long = &H2
Public Const WM_HOTKEY           As Long = &H312
Public Const GWL_WNDPROC         As Long = -4
Public Const WAIT_OBJECT_0       As Long = 0
Public Const INFINITE            As Long = -1&
Public Const GA_ROOT             As Long = 2
Public Const WAIT_TIMEOUT        As Long = &H102&
Public Const DESKTOP_ALL         As Long = 511
Public Const WAIT_IO_COMPLETION  As Long = &HC0&
Public Const THREAD_SET_CONTEXT  As Long = &H10
Public Const WM_SETTEXT          As Long = &HC
 
Public Type STARTUPINFO
    cb              As Long
    lpReserved      As Long
    lpDesktop       As Long
    lpTitle         As Long
    dwX             As Long
    dwY             As Long
    dwXSize         As Long
    dwYSize         As Long
    dwXCountChars   As Long
    dwYCountChars   As Long
    dwFillAttribute As Long
    dwFlags         As Long
    wShowWindow     As Integer
    cbReserved2     As Integer
    lpReserved2     As Long
    hStdInput       As Long
    hStdOutput      As Long
    hStdError       As Long
End Type
 
Public Type PROCESS_INFORMATION
    hProcess        As Long
    hThread         As Long
    dwProcessId     As Long
    dwThreadId      As Long
End Type
 
Public Type tUserThreadData
    hEvent          As Long
End Type
 
Private Type tEnumWndData
    lPID            As Long
    hWnd            As Long
End Type
 
Private Type tAPCCallbackData
    lFuncID         As Long
    vParams()       As Variant
    lRetValue       As Long
    hCallerThread   As Long
End Type
 
Public Declare Function OpenThread Lib "kernel32" ( _
                        ByVal dwDesiredAccess As Long, _
                        ByVal bInheritHandle As Long, _
                        ByVal dwThreadId As Long) As Long
Public Declare Function WaitForSingleObjectEx Lib "kernel32" ( _
                        ByVal hHandle As Long, _
                        ByVal dwMilliseconds As Long, _
                        ByVal bAlertable As Long) As Long
Public Declare Function SleepEx Lib "kernel32" ( _
                        ByVal dwMilliseconds As Long, _
                        ByVal bAlertable As Long) As Long
Public Declare Function GetProcessId Lib "kernel32" ( _
                        ByVal hProcess As Long) As Long
Public Declare Function GetMem4 Lib "msvbvm60" ( _
                        ByRef pSrc As Any, _
                        ByRef pDst As Any) As Long
Public Declare Function SetEvent Lib "kernel32" ( _
                        ByVal hEvent As Long) As Long
Public Declare Function CreateEvent Lib "kernel32" _
                        Alias "CreateEventW" ( _
                        ByRef lpEventAttributes As Any, _
                        ByVal bManualReset As Long, _
                        ByVal bInitialState As Long, _
                        ByVal lpName As Long) As Long
Public Declare Function CloseHandle Lib "kernel32" ( _
                        ByVal hObject As Long) As Long
Public Declare Function GetThreadDesktop Lib "user32" ( _
                        ByVal dwThread As Long) As Long
Public Declare Function CreateDesktop Lib "user32" _
                        Alias "CreateDesktopW" ( _
                        ByVal lpszDesktop As Long, _
                        ByVal lpszDevice As Long, _
                        ByRef pDevmode As Any, _
                        ByVal dwFlags As Long, _
                        ByVal dwDesiredAccess As Long, _
                        ByRef lpsa As Any) As Long
Public Declare Function SwitchDesktop Lib "user32" ( _
                        ByVal hDesktop As Long) As Long
Public Declare Function SetThreadDesktop Lib "user32" ( _
                        ByVal hDesktop As Long) As Long
Public Declare Function CloseDesktop Lib "user32" ( _
                        ByVal hDesktop As Long) As Long
Public Declare Function OpenDesktop Lib "user32" _
                        Alias "OpenDesktopW" ( _
                        ByVal lpszDesktop As Long, _
                        ByVal dwFlags As Long, _
                        ByVal fInherit As Long, _
                        ByVal dwDesiredAccess As Long) As Long
Public Declare Function RegisterHotKey Lib "user32" ( _
                        ByVal hWnd As Long, _
                        ByVal id As Long, _
                        ByVal fsModifiers As Long, _
                        ByVal vk As Long) As Long
Public Declare Function SetWindowLong Lib "user32" _
                        Alias "SetWindowLongW" ( _
                        ByVal hWnd As Long, _
                        ByVal nIndex As Long, _
                        ByVal dwNewLong As Long) As Long
Public Declare Function CreateProcess Lib "kernel32" _
                        Alias "CreateProcessW" ( _
                        ByVal lpApplicationName As Long, _
                        ByVal lpCommandLine As Long, _
                        ByRef lpProcessAttributes As Long, _
                        ByRef lpThreadAttributes As Long, _
                        ByVal bInheritHandles As Long, _
                        ByVal dwCreationFlags As Long, _
                        ByRef lpEnvironment As Any, _
                        ByVal lpCurrentDriectory As Long, _
                        ByRef lpStartupInfo As STARTUPINFO, _
                        ByRef lpProcessInformation As PROCESS_INFORMATION) As Long
Public Declare Function CallWindowProc Lib "user32" _
                        Alias "CallWindowProcW" ( _
                        ByVal lpPrevWndFunc As Long, _
                        ByVal hWnd As Long, _
                        ByVal Msg As Long, _
                        ByVal wParam As Long, _
                        ByVal lParam As Long) As Long
Public Declare Function SetWindowSubclass Lib "Comctl32" ( _
                        ByVal hWnd As Long, _
                        ByVal pfnSubclass As Long, _
                        ByVal uIdSubclass As Long, _
                        ByRef dwRefData As Any) As Long
Public Declare Function RemoveWindowSubclass Lib "Comctl32" ( _
                        ByVal hWnd As Long, _
                        ByVal pfnSubclass As Long, _
                        ByVal uIdSubclass As Long) As Long
Public Declare Function DefSubclassProc Lib "Comctl32" ( _
                        ByVal hWnd As Long, _
                        ByVal uMsg As Long, _
                        ByVal wParam As Long, _
                        ByVal lParam As Long) As Long
Public Declare Function UnregisterHotKey Lib "user32" ( _
                        ByVal hWnd As Long, _
                        ByVal id As Long) As Long
Public Declare Function FindWindow Lib "user32" _
                        Alias "FindWindowW" ( _
                        ByVal lpClassName As Long, _
                        ByVal lpWindowName As Long) As Long
Public Declare Function TerminateProcess Lib "kernel32" ( _
                        ByVal hProcess As Long, _
                        ByVal uExitCode As Long) As Long
Public Declare Function GetAncestor Lib "user32" ( _
                        ByVal hWnd As Long, _
                        ByVal gaFlags As Long) As Long
Public Declare Function EndTask Lib "user32" ( _
                        ByVal hWnd As Long, _
                        ByVal fShutDown As Long, _
                        ByVal fForce As Long) As Long
Public Declare Function QueueUserAPC Lib "kernel32" ( _
                        ByVal pfnAPC As Long, _
                        ByVal hThread As Long, _
                        ByRef dwData As Any) As Long
Public Declare Function EnumWindows Lib "user32" ( _
                        ByVal lpEnumFunc As Long, _
                        ByVal lParam As Long) As Long
Public Declare Function GetWindowThreadProcessId Lib "user32" ( _
                        ByVal hWnd As Long, _
                        ByRef lpdwProcessId As Long) As Long
Public Declare Function SendMessage Lib "user32" _
                        Alias "SendMessageW" ( _
                        ByVal hWnd As Long, _
                        ByVal wMsg As Long, _
                        ByVal wParam As Long, _
                        ByRef lParam As Any) As Long
Public Declare Sub GetStartupInfo Lib "kernel32" _
                   Alias "GetStartupInfoW" ( _
                   ByRef lpStartupInfo As STARTUPINFO)
                
Private Enum FNID
    FNID_FINDWINDOW
    FNID_CLOSEPROCESS
    FNID_GETTOPHANDLE
    FNID_SETCAPTION
End Enum
                        
Private m_hNewDesktop   As Long
Private m_hOldDesktop   As Long
Private m_hCurDesktop   As Long
 
Public Sub AbnormalTermination( _
           ByVal hProcess As Long)
               
    TerminateProcess hProcess, 0
    WaitForSingleObjectEx hProcess, INFINITE, 0
                   
End Sub
 
Public Function CloseProcess( _
                ByVal hThread As Long, _
                ByVal hProcess As Long) As Boolean
    CloseProcess = APCDispatcher(hThread, FNID_CLOSEPROCESS, hProcess)
End Function
 
Public Function RunProcess( _
                ByRef sName As String) As Long
    Dim tSI As STARTUPINFO
    Dim tPI As PROCESS_INFORMATION
    
    GetStartupInfo tSI
    
    tSI.lpDesktop = StrPtr(DESKTOP_NAME)
    
    If CreateProcess(StrPtr(sName), 0, 0, 0, 0, 0, ByVal 0&, ByVal 0&, tSI, tPI) = 0 Then
        Exit Function
    End If
    
    CloseHandle tPI.hThread
    
    RunProcess = tPI.hProcess
    
End Function
 
Public Function FindWindowInNewDesktop( _
                ByVal hThread As Long, _
                ByVal sClassName As String, _
                ByVal sWindowName As String) As Long
    FindWindowInNewDesktop = APCDispatcher(hThread, FNID_FINDWINDOW, sClassName, sWindowName)
End Function
 
Public Function GetHandleOfTopWindow( _
                ByVal hThread As Long, _
                ByVal hProcess As Long) As Long
    GetHandleOfTopWindow = APCDispatcher(hThread, FNID_GETTOPHANDLE, hProcess)
End Function
 
Public Function SetTopWindowCaption( _
                ByVal hThread As Long, _
                ByVal hProcess As Long, _
                ByVal sCaption As String) As Long
    SetTopWindowCaption = APCDispatcher(hThread, FNID_SETCAPTION, hProcess, sCaption)
End Function
 
' // This function calls procedure in other thread and wait for completion
Private Function APCDispatcher( _
                 ByVal hThread As Long, _
                 ByVal lFuncID As Long, _
                 ParamArray vParams() As Variant) As Long
    Dim pParams(3)  As Long
    
    pParams(0) = lFuncID
    
    GetMem4 ByVal VarPtr(lFuncID) + 4, pParams(1)
    GetMem4 ByVal pParams(1), pParams(1)
    
    pParams(3) = OpenThread(THREAD_SET_CONTEXT, 0, App.ThreadID)
    
    If pParams(3) = 0 Then
        MsgBox "Unable to open thread for APC", vbCritical
        Exit Function
    End If
    
    If QueueUserAPC(AddressOf DesktopAPCCallback, hThread, pParams(0)) Then
        SleepEx INFINITE, 1
    End If
    
    CloseHandle pParams(3)
    
    APCDispatcher = pParams(2)
    
End Function
 
' // This procedure called in new desktop
Private Sub DesktopAPCCallback( _
            ByRef tParams As tAPCCallbackData)
    
    Select Case tParams.lFuncID
    Case FNID_FINDWINDOW
        tParams.lRetValue = FindWindow(StrPtr(tParams.vParams(0)), StrPtr(tParams.vParams(1)))
    Case FNID_CLOSEPROCESS
        tParams.lRetValue = CloseProcessInThread(tParams.vParams(0))
    Case FNID_GETTOPHANDLE
        tParams.lRetValue = GetTopHandleInThread(tParams.vParams(0))
    Case FNID_SETCAPTION
        tParams.lRetValue = SetCaptionInThread(tParams.vParams(0), tParams.vParams(1))
    End Select
        
    QueueUserAPC AddressOf MainAPCCallback, tParams.hCallerThread, ByVal 0&
    
End Sub
 
Private Function SetCaptionInThread( _
                 ByVal hProcess As Long, _
                 ByVal sCaption As String) As Long
    Dim hWnd    As Long
    
    hWnd = GetTopHandleInThread(hProcess)
    
    If hWnd Then
        SetCaptionInThread = SendMessage(hWnd, WM_SETTEXT, 0, ByVal StrPtr(sCaption))
    End If
    
End Function
 
Private Function GetTopHandleInThread( _
                 ByVal hProcess As Long) As Long
    Dim tData   As tEnumWndData
    
    tData.lPID = GetProcessId(hProcess)
    
    EnumWindows AddressOf EnumWndProc, VarPtr(tData)
    
    GetTopHandleInThread = tData.hWnd
    
End Function
 
Private Function CloseProcessInThread( _
                 ByVal hProcess As Long) As Long
    Dim hWnd    As Long
    
    hWnd = GetTopHandleInThread(hProcess)
    
    If hWnd Then
        CloseProcessInThread = EndTask(hWnd, 0, 1)
    End If
    
End Function
 
Private Function EnumWndProc( _
                 ByVal hWnd As Long, _
                 ByRef tData As tEnumWndData) As Long
    Dim lWndPID As Long
    
    GetWindowThreadProcessId hWnd, lWndPID
    
    If tData.lPID <> lWndPID Then
        EnumWndProc = 1
    Else
        tData.hWnd = hWnd
    End If
    
End Function
 
' // This procedure called in current desktop
' // Isn't used. Just to return from SleepEx
Private Sub MainAPCCallback( _
            ByVal lUnused As Long)
End Sub
 
Public Function ThreadProc( _
                ByRef tData As tUserThreadData) As Long
    
    ' // Loop until we SetEvent. Skip APCs
    Do While WaitForSingleObjectEx(tData.hEvent, INFINITE, 1) = WAIT_IO_COMPLETION
    Loop
    
End Function
 
' // Switch caller thread to desktop
Public Sub SwitchToOtherDesktop()
    If m_hNewDesktop Then
        SetThreadDesktop m_hNewDesktop
    End If
End Sub
 
Public Sub SwitchToMainDesktop()
    SwitchDesktop m_hOldDesktop
    m_hCurDesktop = m_hOldDesktop
End Sub
 
Public Function SubclassWndProc( _
                ByVal hWnd As Long, _
                ByVal lMsg As Long, _
                ByVal wParam As Long, _
                ByVal lParam As Long, _
                ByVal uIdSubclass As Long, _
                ByVal dwRefData As Long) As Long
    
    Select Case lMsg
    Case WM_HOTKEY
        If wParam = 1 Then
            If m_hCurDesktop = m_hOldDesktop Then
                SwitchDesktop m_hNewDesktop:    m_hCurDesktop = m_hNewDesktop
            Else
                SwitchDesktop m_hOldDesktop:    m_hCurDesktop = m_hOldDesktop
            End If
        End If
    Case Else
        SubclassWndProc = DefSubclassProc(hWnd, lMsg, wParam, lParam)
    End Select
    
End Function
 
Public Function InitDesktop() As Boolean
    
    If m_hNewDesktop = 0 Then
        
        m_hOldDesktop = GetThreadDesktop(App.ThreadID)
        m_hNewDesktop = OpenDesktop(StrPtr(DESKTOP_NAME), 0, 0, DESKTOP_ALL)    '
        m_hCurDesktop = m_hOldDesktop
        
        If m_hNewDesktop = 0 Then
            m_hNewDesktop = CreateDesktop(StrPtr(DESKTOP_NAME), 0, ByVal 0&, 0, DESKTOP_ALL, ByVal 0&)  '
        End If
        
    End If
    
    InitDesktop = m_hNewDesktop
    
End Function
 
Public Function DestroyDesktop() As Boolean
    
    If m_hNewDesktop Then
        If CloseDesktop(m_hNewDesktop) Then
            DestroyDesktop = True
            m_hNewDesktop = 0
        End If
    Else
        DestroyDesktop = True
    End If
    
    m_hCurDesktop = m_hOldDesktop
    
End Function
Вложения
Тип файла: zip RunInNewDesktop.zip (28.6 Кб, 26 просмотров)
2
7 / 7 / 0
Регистрация: 10.07.2015
Сообщений: 69
12.04.2020, 06:54  [ТС]
Thank you very much. You are a real expert professor

You showed a very detailed process..

The delphi code I found online is very simple. I did not expect such a complicated Convert to vb6


Ask another question. ctrl + w switch desktop, sometimes it will not switch。。

Thanks again

Добавлено через 5 минут
Thank you very much. You are a real expert professor

You showed a very detailed process..

The delphi code I found online is very simple. I did not expect such a complicated Convert to vb6


Ask another question. ctrl + w switch desktop, sometimes it will not switch。。

Thanks again
0
Модератор
10048 / 3894 / 883
Регистрация: 22.02.2013
Сообщений: 5,847
Записей в блоге: 79
12.04.2020, 12:46
Цитата Сообщение от xxdoc Посмотреть сообщение
The delphi code I found online is very simple. I did not expect such a complicated Convert to vb6
What's the Delphi code? The communication between threads isn't trivial task if these threads are in the different desktops. I used APC, you can use another technique like the events/pipes/sockets. The most part of the code is just my multithreading module (modMultithreading.bas). The unused procedures (the most part) aren't placed into the executable (like COM/STA things).

Цитата Сообщение от xxdoc Посмотреть сообщение
Ask another question. ctrl + w switch desktop, sometimes it will not switch
The code doesn't check some errors. I think you should analyse the error code of the APIs when you're switching a desktop.
0
7 / 7 / 0
Регистрация: 10.07.2015
Сообщений: 69
13.04.2020, 08:35  [ТС]
thanks. now find the hwnd ,can control the other project in new desktop. this is a good idea can hide third-party programs when showwindow hide does not work。
This will be a perfect way to call third-party programs, let third-party programs run in the background, customers will not find this trick
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
13.04.2020, 08:35
Помогаю со студенческими работами здесь

Ошибка в window.captureEvents(Event.CLICK); window.onClick= handle; function handle(e) { alert(''); return false; }
&lt;script&gt; window.captureEvents(Event.CLICK); window.onClick= handle; function handle(e) { alert(''); return false; } ...

Application.Handle выдает identifier idents no member "Handle", на Дельфи всё работает
Не компилируется к примеру код: begin MessageDlg('Уже поздно. Будь послушным мальчиком. '+ 'Туши свет и вали спать!',...

Protected abstract virtual base pure virtual private destructor
Хай, all) Вопрос не для начинающих и дурацкий) В разделе для экспертов публиковать не стал, чтобы не засорять его) Наткнулся тут на...

Что брать посоветуете? HP Omni 27-1054 Desktop PC или HP Omni 220-1185qd Desktop PC?
Привет. HP Omni 220-1185qd Desktop PC Operating system - Windows 7 Home Premium Processor - 3rd Generation Intel(R)...

Не могу разобраться с папкой Desktop и скрытой папкой Public Desktop
Я хочу получить возможность взаимодействия с ярлыками. Одни ярлыки находятся по адресу c:\users\user\Desktop и к ним претензий нет. Но есть...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
17
Ответ Создать тему
Новые блоги и статьи
Воспроизведение звукового файла с помощью SDL3_mixer при касании экрана Android
8Observer8 26.01.2026
Содержание блога SDL3_mixer - это библиотека я для воспроизведения аудио. В отличие от инструкции по добавлению текста код по проигрыванию звука уже содержится в шаблоне примера. Нужно только. . .
Установка Android SDK, NDK, JDK, CMake и т.д.
8Observer8 25.01.2026
Содержание блога Перейдите по ссылке: https:/ / developer. android. com/ studio и в самом низу страницы кликните по архиву "commandlinetools-win-xxxxxx_latest. zip" Извлеките архив и вы увидите. . .
Вывод текста со шрифтом TTF на Android с помощью библиотеки SDL3_ttf
8Observer8 25.01.2026
Содержание блога Если у вас не установлены Android SDK, NDK, JDK, и т. д. то сделайте это по следующей инструкции: Установка Android SDK, NDK, JDK, CMake и т. д. Сборка примера Скачайте. . .
Использование SDL3-callbacks вместо функции main() на Android, Desktop и WebAssembly
8Observer8 24.01.2026
Содержание блога Если вы откроете примеры для начинающих на официальном репозитории SDL3 в папке: examples, то вы увидите, что все примеры используют следующие четыре обязательные функции, а. . .
моя боль
iceja 24.01.2026
Выложила интерполяцию кубическими сплайнами www. iceja. net REST сервисы временно не работают, только через Web. Написала за 56 рабочих часов этот сайт с нуля. При помощи perplexity. ai PRO , при. . .
Модель сукцессии микоризы
anaschu 24.01.2026
Решили писать научную статью с неким РОманом
http://iceja.net/ математические сервисы
iceja 20.01.2026
Обновила свой сайт http:/ / iceja. net/ , приделала Fast Fourier Transform экстраполяцию сигналов. Однако предсказывает далеко не каждый сигнал (см ограничения http:/ / iceja. net/ fourier/ docs ). Также. . .
http://iceja.net/ сервер решения полиномов
iceja 18.01.2026
Выкатила http:/ / iceja. net/ сервер решения полиномов (находит действительные корни полиномов методом Штурма). На сайте документация по API, но скажу прямо VPS слабенький и 200 000 полиномов. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru