Форум программистов, компьютерный форум, киберфорум
C# для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск  
 
 
Рейтинг 4.70/30: Рейтинг темы: голосов - 30, средняя оценка - 4.70
20 / 20 / 6
Регистрация: 18.07.2014
Сообщений: 73

SysListView32 запись значений в чужом окне

18.07.2014, 15:04. Показов 6583. Ответов 26
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Здравствуйте! Ребята помогите пожалуйста с реализацией записи значений в колонки SysListView32 который находится в окне чужой программы. Перечитал много чего - перегуглил, переяндоксил и МСДНил однако рабочей реалиазии не добился, так что прошу меня в выше указанные вещи не отпровлять, а помочь примером именно на c# или пенками в нужную сторону с примерами ))).
Для чего надо: на работе у коллег очень много однотипного ручного ввода причём дублирующего в нескольких программах, меня попросили написать программу которая этот бы самый ввод автоматизировала.
Что есть: упешно получаем дескрипторы нужных окон, контролов и заполняем их, жамкаем клавиши и т.д. (в не активном окне). Каких-либо проблем с получением дескриптора нужного SysListView32 нет.
В чём нужна помощь: После большой кучи операций ввода в сторонней программе появляется окно с SysListView32 в котором имеется 4 колонки и в которые в обязательном порядке нужно внести значения. Вот тут я и встал полностью, пробывал и через посылку сообщений, пробывал копашится в памяти но безуспешно. К своему стыду какой либо боле менее вразумительный код представить вам не могу поэтому прошу дать примерчик как записывать значения в колонки стороннего ListView и если не затруднит как считывать значения именно на c#.
PS с языком c# знаком всего менее месяца, ранее писал на паскале и PHP, приходится изучать и адаптироваться на лету, возможности сменить среду разработки нет из-за сурового отдела безопасности.
Всех откликнувшихся заранее благодарю.
0
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
18.07.2014, 15:04
Ответы с готовыми решениями:

SysListView32 в чужом Окне Получить Текст (Win7 x64)
Привет искал в интернете http://blacksus.narod.ru/articles_1_1_6.html http://www.delphisources.ru/forum/showthread.php?t=8592 ...

Как узнать количество столбиков в окне класса SysListView32?
Друзья! Окно такого класса это рабочая область обыкновенной папки windows, это окно класса SysListView32. (см. скриншот). Хэндл окна я...

Рисование в чужом окне
всем привет как рисовать текст в чужом окне не используя своего окна и не имея его

26
20 / 20 / 6
Регистрация: 18.07.2014
Сообщений: 73
23.04.2020, 11:45  [ТС]
Студворк — интернет-сервис помощи студентам
Нарыл у себя в недрах закинутых проектов возможно пригодится
C#
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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
public class Class1
{
 
 
/// <summary>
/// Reads a list view item and returns the
User32.Consts.ListView.LV_ITEM read.
/// </summary>
/// <param name="hWnd"></param>
/// <param name="item"></param>
/// <param name="subItem"></param>
/// <param name="selected"></param>
/// <param name="returnItem"></param>
/// <returns></returns>
public static string ReadListViewItem(
IntPtr hWnd,
int item,
int subItem,
out bool selected,
out User32.Consts.ListView.LV_ITEM returnItem)
{
User32.Consts.ListView.LV_ITEM lvItem;
string retval;
IntPtr hProcess = IntPtr.Zero;
IntPtr lpRemoteBuffer = IntPtr.Zero;
IntPtr lpLocalBuffer = IntPtr.Zero;
IntPtr threadId = IntPtr.Zero;
 
try
{
//create a new "Storage" object
lvItem = new User32.Consts.ListView.LV_ITEM();
 
//create a local buffer
lpLocalBuffer =
Marshal.AllocHGlobal(User32.Consts.CrossProcessMem.dwBufferSize);
 
//create a remote buffer in the other process
lpRemoteBuffer = AllocateMemoryInOtherProcess(hWnd, ref
hProcess);
 
//Create a "Storage" object
// Fill in the LVITEM struct, this is in your own process
// Set the pszText member to somewhere in the remote buffer,
// For the example I used the address imediately following the
LVITEM stuct
lvItem.mask = User32.Consts.ListView.Masks.LVIF_TEXT |
User32.Consts.ListView.Masks.LVIF_STATE;
lvItem.iItem = item;
lvItem.iSubItem = subItem;
lvItem.pszText = (IntPtr)(lpRemoteBuffer.ToInt32() +
Marshal.SizeOf(typeof(User32.Consts.ListView.LV_ITEM)));
lvItem.cchTextMax = 255;
lvItem.stateMask = (uint)(new IntPtr(-1).ToInt32());
 
// process the message using the remote buffer
IntPtr local = ProcessRemoteMessage(
hProcess,
hWnd,
User32.Consts.ListView.Messages.LVM_GETITEM,
IntPtr.Zero,
lpRemoteBuffer,
lpLocalBuffer,
typeof(User32.Consts.ListView.LV_ITEM),
ref lvItem);
 
//set the local buffer to our returned pointer
lpLocalBuffer = local;
 
//convert the pointer back to the structure
User32.Consts.ListView.LV_ITEM lv = new
User32.Consts.ListView.LV_ITEM();
lv =
(User32.Consts.ListView.LV_ITEM)Marshal.PtrToStructure(lpLocalBuffer,
typeof(User32.Consts.ListView.LV_ITEM));
 
returnItem = lv;
 
if (lv.state > 8191)
{
selected = true;
}
else
{
selected = false;
}
 
// At this point the lpLocalBuffer contains the returned
User32.Consts.ListView.LV_ITEM structure
// the next line extracts the text from the buffer into a
managed string
retval = Marshal.PtrToStringAnsi(
(IntPtr)(lpLocalBuffer.ToInt32() +
Marshal.SizeOf(typeof(User32.Consts.ListView.LV_ITEM)))
);
}
finally
{
if (lpLocalBuffer != IntPtr.Zero)
Marshal.FreeHGlobal(lpLocalBuffer);
if (lpRemoteBuffer != IntPtr.Zero)
User32.VirtualFreeEx(hProcess, lpRemoteBuffer, 0,
User32.Consts.CrossProcessMem.MEM_RELEASE);
if (hProcess != IntPtr.Zero)
User32.CloseHandle(hProcess);
}
return retval;
}
 
/// <summary>
/// Sets the state of a listview item
/// </summary>
/// <param name="hWnd">handle to the listview</param>
/// <param name="item">Item to manipulate</param>
/// <param name="subItem">subitem should generally be set to
zero</param>
/// <param name="selected">value of the Checked state</param>
/// <param name="activate">Activates the item</param>
/// <param name="setFocus">Sets focus to the item</param>
/// <param name="selectItem">Selects the item (highlights
it)</param>
/// <param name="checkItem">Attempts to Check the item</param>
public static void SetListViewItem(
IntPtr hWnd,
int item,
int subItem,
bool selected,
bool activate,
bool setFocus,
bool selectItem,
bool checkItem ) //add a string text parameter here
{
User32.Consts.ListView.LV_ITEM lvItem;
string retval;
IntPtr hProcess = IntPtr.Zero;
IntPtr lpRemoteBuffer = IntPtr.Zero;
IntPtr lpLocalBuffer = IntPtr.Zero;
IntPtr threadId = IntPtr.Zero;
 
try
{
bool tmp = false;
//Read the list view item to retrieve the LV_ITEM struct
from the existing item
ReadListViewItem(hWnd, item, subItem, out tmp, out lvItem);
 
//create a local buffer
lpLocalBuffer =
Marshal.AllocHGlobal(User32.Consts.CrossProcessMem.dwBufferSize);
 
//create a remote buffer in the other process
lpRemoteBuffer = AllocateMemoryInOtherProcess(hWnd, ref
hProcess);
 
 
#region Set Focus Item
if (setFocus)
{
lvItem.mask = User32.Consts.ListView.Masks.LVIF_STATE;
lvItem.stateMask =
User32.Consts.ListView.StateMasks.LVIS_FOCUSED;
lvItem.state =
User32.Consts.ListView.StateMasks.LVIS_FOCUSED;
 
// send the message to the process using the remote
buffer
IntPtr local = ProcessRemoteMessage(
hProcess, //process
hWnd,//handle
User32.Consts.ListView.Messages.LVM_SETITEM,//message
IntPtr.Zero, //Wparam
lpRemoteBuffer, //remote buffer
lpLocalBuffer, //local buffer
typeof(User32.Consts.ListView.LV_ITEM), //type to
send
ref lvItem); //return object
}
#endregion Set Focus Item
 
#region Select Item
if (selectItem)
{
lvItem.mask = User32.Consts.ListView.Masks.LVIF_STATE;
lvItem.stateMask =
User32.Consts.ListView.StateMasks.LVIS_SELECTED;
lvItem.state =
User32.Consts.ListView.StateMasks.LVIS_SELECTED;
 
// send the message to the process using the remote
buffer
IntPtr local = ProcessRemoteMessage(
hProcess, //process
hWnd,//handle
User32.Consts.ListView.Messages.LVM_SETITEM,//message
IntPtr.Zero, //Wparam
lpRemoteBuffer, //remote buffer
lpLocalBuffer, //local buffer
typeof(User32.Consts.ListView.LV_ITEM), //type to
send
ref lvItem); //return object
}
#endregion Select Item
 
#region Activate Item
if (activate)
{
lvItem.mask = User32.Consts.ListView.Masks.LVIF_STATE;
lvItem.stateMask =
User32.Consts.ListView.StateMasks.LVIS_ACTIVATING;
lvItem.state =
User32.Consts.ListView.StateMasks.LVIS_ACTIVATING;
 
// send the message to the process using the remote
buffer
IntPtr local = ProcessRemoteMessage(
hProcess, //process
hWnd,//handle
User32.Consts.ListView.Messages.LVM_SETITEM,//message
IntPtr.Zero, //Wparam
lpRemoteBuffer, //remote buffer
lpLocalBuffer, //local buffer
typeof(User32.Consts.ListView.LV_ITEM), //type to
send
ref lvItem); //return object
}
#endregion Activate Item
 
#region Check Item
if (checkItem)
{
lvItem.mask = User32.Consts.ListView.Masks.LVIF_STATE;
lvItem.stateMask =
User32.Consts.ListView.StateMasks.LVIS_STATEIMAGEMASK;
 
if (selected)
{
//>8192
lvItem.state = 8192;
}
else
{
lvItem.state = 4096;
}
 
 
// send the message to the process using the remote
buffer
ProcessRemoteMessage(
hProcess, //process
hWnd,//handle
User32.Consts.ListView.Messages.LVM_SETITEM,//message
IntPtr.Zero, //Wparam
lpRemoteBuffer, //remote buffer
lpLocalBuffer, //local buffer
typeof(User32.Consts.ListView.LV_ITEM), //type to
send
ref lvItem); //return object
}
#endregion CheckItem
 
//add a region for changing the text if it is not null here
}
finally
{
if (lpLocalBuffer != IntPtr.Zero)
Marshal.FreeHGlobal(lpLocalBuffer);
if (lpRemoteBuffer != IntPtr.Zero)
User32.VirtualFreeEx(hProcess, lpRemoteBuffer, 0,
User32.Consts.CrossProcessMem.MEM_RELEASE);
if (hProcess != IntPtr.Zero)
User32.CloseHandle(hProcess);
}
return retval;
}
 
/// <summary>
/// Calls
/// WriteObjectToOtherProcessMemory,
/// SendMessageToRemoteBuffer and
/// ReadRemoteBufferIntoLocalBuffer
/// in one call.
/// </summary>
/// <param name="hProcess"></param>
/// <param name="hWnd"></param>
/// <param name="message"></param>
/// <param name="wParam"></param>
/// <param name="lpRemoteBuffer"></param>
/// <param name="lpLocalBuffer"></param>
/// <param name="obj"></param>
/// <returns></returns>
public static IntPtr ProcessRemoteMessage(
IntPtr hProcess,
IntPtr hWnd,
uint message,
IntPtr wParam,
IntPtr lpRemoteBuffer,
IntPtr lpLocalBuffer,
Type typeToMarshal,
ref User32.Consts.ListView.LV_ITEM obj)
{
 
//Write to the other process memory
WriteObjectToOtherProcessMemory(
hProcess,
lpRemoteBuffer,
typeToMarshal,
ref obj);
 
SendMessageToRemoteBuffer(
hWnd,
message,
wParam,
lpRemoteBuffer);
 
IntPtr retVal = ReadRemoteBufferIntoLocalBuffer(
hProcess,
lpRemoteBuffer,
lpLocalBuffer);
 
return retVal;
}
 
/// <summary>
/// Writes an object (managed buffer) into a different unmanaged
/// process memory
/// </summary>
/// <param name="hProcess"></param>
/// <param name="lpRemoteBuffer"></param>
/// <param name="obj"></param>
/// <returns></returns>
public static bool WriteObjectToOtherProcessMemory(
IntPtr hProcess,
IntPtr lpRemoteBuffer,
Type typeToMarshal,
ref User32.Consts.ListView.LV_ITEM obj)
{
bool bSuccess;
 
bSuccess = User32.WriteProcessMemory(
hProcess,
lpRemoteBuffer,
ref obj,
Marshal.SizeOf(typeToMarshal), IntPtr.Zero);
 
if (!bSuccess)
throw new SystemException("Failed to write to process
memory");
 
return bSuccess;
}
 
/// <summary>
/// Sends a Message to an unmanaged process window
/// </summary>
/// <param name="hWnd"></param>
/// <param name="message"></param>
/// <param name="wParam"></param>
/// <param name="lpRemoteBuffer"></param>
public static void SendMessageToRemoteBuffer(
IntPtr hWnd,
uint message,
IntPtr wParam,
IntPtr lpRemoteBuffer)
{
object o = new object();
 
HandleRef handleRef = new HandleRef(o, hWnd);
 
IntPtr result = IntPtr.Zero;
 
User32.SendMessageTimeout(
handleRef,
message,
wParam,
lpRemoteBuffer,
new
UIntPtr(User32.Consts.SendMessageTimeOutFlags.SMTO_ABORTIFHUNG),
Properties.Settings.Default.SendMessageBaseTimeOut,
out result);
 
int r = result.ToInt32();
 
}
 
/// <summary>
/// Reads a remote buffer and places its contents into a local
(managed) buffer. The
/// method returns the local buffer.
/// </summary>
/// <param name="hProcess"></param>
/// <param name="lpRemoteBuffer"></param>
/// <param name="lpLocalBuffer"></param>
/// <returns></returns>
public static IntPtr ReadRemoteBufferIntoLocalBuffer(
IntPtr hProcess,
IntPtr lpRemoteBuffer,
IntPtr lpLocalBuffer)
{
bool bSuccess = false;
 
bSuccess = User32.ReadProcessMemory(
hProcess,
lpRemoteBuffer,
lpLocalBuffer,
User32.Consts.CrossProcessMem.dwBufferSize,
IntPtr.Zero);
 
if (!bSuccess)
throw new SystemException("Failed to read from process
memory");
 
return lpLocalBuffer;
}
 
 
}
 
public class User32
{
 
[DllImport("user32")]
public static extern IntPtr GetWindowThreadProcessId(IntPtr hWnd, out
int lpwdProcessID);
 
[DllImport("kernel32")]
public static extern IntPtr OpenProcess(uint dwDesiredAccess, bool
bInheritHandle,
int dwProcessId);
 
[DllImport("kernel32")]
public static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr
lpAddress,
int dwSize, uint flAllocationType, uint flProtect);
 
[DllImport("kernel32")]
public static extern bool VirtualFreeEx(IntPtr hProcess, IntPtr
lpAddress, int dwSize,
uint dwFreeType);
 
[DllImport("kernel32")]
public static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr
lpBaseAddress,
ref User32.Consts.ListView.LV_ITEM buffer, int dwSize, IntPtr
lpNumberOfBytesWritten);
 
[DllImport("kernel32")]
public static extern bool CloseHandle(IntPtr hObject);
}
если разыщу что то ещё выкину

Добавлено через 6 минут
ещё вот такое осталось
C#
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
public class Class1
{
/// <summary>
/// Writes an object (managed buffer) into a different unmanaged
/// process memory
/// </summary>
/// <param name="hProcess">Remote Process</param>
/// <param name="lpRemoteBuffer">Remote Memory Address (base
address)</param>
/// <param name="obj">object to write</param>
/// <returns>Bool if the method was successful</returns>
public static bool WriteObjectToOtherProcessMemory(
IntPtr hProcess,
IntPtr lpRemoteBuffer,
Type typeToMarshal,
ref StringBuilder obj)
{
bool bSuccess;
 
//call the WriteProcessMemory (slightly different then
//the other methods. We use the Capacity value of
//the stringbuilder for the 'size' parameter
bSuccess = User32.WriteProcessMemory(
hProcess,
lpRemoteBuffer,
obj, obj.Capacity, IntPtr.Zero);
 
if (!bSuccess)
throw new SystemException("Failed to write to process memory");
 
return bSuccess;
}
 
 
public static string SetListViewItem(
IntPtr hWnd,
int item,
int subItem,
string text,
bool selected,
bool activate,
bool setFocus,
bool highlightItem,
bool checkItem,
bool manipulateOnlySubItem)
{
User32.Consts.ListView.LV_ITEM lvItem;
string retval;
IntPtr hProcess = IntPtr.Zero;
IntPtr lpRemoteBuffer = IntPtr.Zero;
IntPtr lpLocalBuffer = IntPtr.Zero;
IntPtr lpRemoteBufferWithText = IntPtr.Zero;
IntPtr threadId = IntPtr.Zero;
 
try
{
int tmpSubItem = subItem;
bool tmp = false;
ReadListViewItem(hWnd, item, subItem, out tmp, out lvItem);
 
//create a local buffer
lpLocalBuffer =
Marshal.AllocHGlobal(User32.Consts.CrossProcessMem.dwBufferSize * 2);
 
//create a remote buffer in the other process
lpRemoteBuffer = AllocateMemoryInOtherProcess(hWnd, ref
hProcess);
 
if (!manipulateOnlySubItem)
{
subItem = item;
}
 
#region Set Focus Item
if (setFocus)
{
lvItem.mask = User32.Consts.ListView.Masks.LVIF_STATE;
lvItem.stateMask =
User32.Consts.ListView.StateMasks.LVIS_FOCUSED;
lvItem.state =
User32.Consts.ListView.StateMasks.LVIS_FOCUSED;
 
// process the message using the remote buffer
IntPtr local = ProcessRemoteMessage(
hProcess, //process
hWnd,//handle
User32.Consts.ListView.Messages.LVM_SETITEM,//message
IntPtr.Zero, //Wparam
lpRemoteBuffer, //remote buffer
lpLocalBuffer, //local buffer
typeof(User32.Consts.ListView.LV_ITEM), //type to send
ref lvItem); //return object
}
#endregion Set Focus Item
 
#region Select Item
if (highlightItem)
{
lvItem.mask = User32.Consts.ListView.Masks.LVIF_STATE;
lvItem.stateMask =
User32.Consts.ListView.StateMasks.LVIS_SELECTED;
lvItem.state =
User32.Consts.ListView.StateMasks.LVIS_SELECTED;
 
// process the message using the remote buffer
IntPtr local = ProcessRemoteMessage(
hProcess, //process
hWnd,//handle
User32.Consts.ListView.Messages.LVM_SETITEM,//message
IntPtr.Zero, //Wparam
lpRemoteBuffer, //remote buffer
lpLocalBuffer, //local buffer
typeof(User32.Consts.ListView.LV_ITEM), //type to send
ref lvItem); //return object
}
#endregion Select Item
 
#region Activate Item
if (activate)
{
lvItem.mask = User32.Consts.ListView.Masks.LVIF_STATE;
lvItem.stateMask =
User32.Consts.ListView.StateMasks.LVIS_ACTIVATING;
lvItem.state =
User32.Consts.ListView.StateMasks.LVIS_ACTIVATING;
 
// process the message using the remote buffer
IntPtr local = ProcessRemoteMessage(
hProcess, //process
hWnd,//handle
User32.Consts.ListView.Messages.LVM_SETITEM,//message
IntPtr.Zero, //Wparam
lpRemoteBuffer, //remote buffer
lpLocalBuffer, //local buffer
typeof(User32.Consts.ListView.LV_ITEM), //type to send
ref lvItem); //return object
}
#endregion Activate Item
 
#region Check Item
if (checkItem)
{
lvItem.mask = User32.Consts.ListView.Masks.LVIF_STATE;
lvItem.stateMask =
User32.Consts.ListView.StateMasks.LVIS_STATEIMAGEMASK;
 
if (selected)
{
//>8192
lvItem.state = 8192;
}
else
{
lvItem.state = 4096;
}
 
 
// process the message using the remote buffer
ProcessRemoteMessage(
hProcess, //process
hWnd,//handle
User32.Consts.ListView.Messages.LVM_SETITEM,//message
IntPtr.Zero, //Wparam
lpRemoteBuffer, //remote buffer
lpLocalBuffer, //local buffer
typeof(User32.Consts.ListView.LV_ITEM), //type to send
ref lvItem); //return object
}
#endregion CheckItem
 
if (!manipulateOnlySubItem)
{
subItem = tmpSubItem;
}
 
#region Text
 
 
//Create a "Storage" object
// Fill in the LVITEM struct, this is in your own process
// Set the pszText member to somewhere in the remote buffer,
// Use the address imediately following the LVITEM stuct
// to store the text for retrieve by the ListView upon
// sending the message
lvItem.mask = User32.Consts.ListView.Masks.LVIF_TEXT;
lvItem.iSubItem = subItem;
lvItem.iItem = item;
 
//Allocate the buffer (make a 1mb area)
IntPtr remoteBufferLVITEM = lpRemoteBuffer;
 
//assign the text location in the remote buffer
IntPtr remoteBufferText = new
IntPtr(remoteBufferLVITEM.ToInt32() +
Marshal.SizeOf(typeof(User32.Consts.ListView.LV_ITEM)));
 
//assign our stringbuilder the text value
StringBuilder builderText = new StringBuilder(text);
lvItem.cchTextMax = builderText.Capacity;
 
//set the text pointer to point to the text
//in the remote buffer
lvItem.pszText = remoteBufferText;
 
//Write the LV_ITEM Struct to the remote memory location
WriteObjectToOtherProcessMemory(
hProcess,
remoteBufferLVITEM,
typeof(User32.Consts.ListView.LV_ITEM),
ref lvItem);
 
//write the text to the remote memory location
WriteObjectToOtherProcessMemory(
hProcess,
remoteBufferText,
typeof(StringBuilder),
ref builderText);
 
//send the message to have the ListView read the text
//from the memory location
SendMessageToRemoteBuffer(
hWnd,
User32.Consts.ListView.Messages.LVM_SETITEM,
IntPtr.Zero,
remoteBufferLVITEM);
 
//used to check the value after the write
 
//IntPtr remoteBufferValue = ReadRemoteBufferIntoLocalBuffer(
// hProcess,
// lpRemoteBuffer,
// lpLocalBuffer);
 
//string value = Marshal.PtrToStringAnsi(
// (IntPtr)(lpLocalBuffer.ToInt32() +
Marshal.SizeOf(typeof(User32.Consts.ListView.LV_ITEM)))
// );
 
#endregion Text
 
retval = string.Empty;
}
finally
{
if (lpLocalBuffer != IntPtr.Zero)
Marshal.FreeHGlobal(lpLocalBuffer);
if (lpRemoteBuffer != IntPtr.Zero)
User32.VirtualFreeEx(hProcess, lpRemoteBuffer, 0,
User32.Consts.CrossProcessMem.MEM_RELEASE);
if (hProcess != IntPtr.Zero)
User32.CloseHandle(hProcess);
}
return retval;
}
}
 
 
public class User32
{
//it is important to have the MarshalAs attribute for the
//StringBuilder here otherwise the system can
//not Marshal the StringBuilder
[DllImport("kernel32")]
public static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr
lpBaseAddress,
[MarshalAs(UnmanagedType.LPStr)] StringBuilder buffer, int dwSize,
IntPtr lpNumberOfBytesWritten);
 
}
1
20 / 20 / 6
Регистрация: 18.07.2014
Сообщений: 73
23.04.2020, 12:47  [ТС]
Лучший ответ Сообщение было отмечено Почтальон как решение

Решение

И вот отрыл наверное самое интересное где можно много подчерпнуть как чего и зачем вдруг пригодится покрайне мере лист виев работает практически аналогично
Вложения
Тип файла: rar тривиев почерпнуть можно кучу.rar (4.9 Кб, 24 просмотров)
0
управление сложностью
 Аватар для Почтальон
1693 / 1306 / 259
Регистрация: 22.03.2015
Сообщений: 7,545
Записей в блоге: 5
23.04.2020, 12:52
Спасибо, думаю очень пригодится.
0
управление сложностью
 Аватар для Почтальон
1693 / 1306 / 259
Регистрация: 22.03.2015
Сообщений: 7,545
Записей в блоге: 5
23.04.2020, 18:43
Что-то шляпа какая-то
Удалось получить ListView, но информация почему-то не полная.

0
управление сложностью
 Аватар для Почтальон
1693 / 1306 / 259
Регистрация: 22.03.2015
Сообщений: 7,545
Записей в блоге: 5
23.04.2020, 18:45
Из списка могу получить только дату, т.е. по сути только первый столбец
0
управление сложностью
 Аватар для Почтальон
1693 / 1306 / 259
Регистрация: 22.03.2015
Сообщений: 7,545
Записей в блоге: 5
23.04.2020, 19:34
Как-то так, вывел через AutomationElement:
0
управление сложностью
 Аватар для Почтальон
1693 / 1306 / 259
Регистрация: 22.03.2015
Сообщений: 7,545
Записей в блоге: 5
23.04.2020, 19:56
Кажется понял, нужно через SendMessage и LVM_GETITEMTEXT, попробую
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
23.04.2020, 19:56

Рисование в чужом окне
Собственно, я понимаю как рисовать, мне больше интересно 2 момента: 1) Если я просто буду рисовать на окне, то при его перерисовке всё...

Клик в чужом окне
Как можно реализовать множественный клик правой кнопкой мыши в чужом окне?

Рисование в чужом окне
Дано окно чужой программы. Требуется что-то на нем нарисовать. Скажем, дырку в том месте, куда мышкой кликнули. Гуглил на эту тему,...

Нажатие кнопки в чужом окне!!!
Помогите пожалуйста написать программу на Delphi нажатие кнопки в окне чужого приложения. Точнее кнопку Кодирование. Приложение в аттаче.

Нажать ctrl+s в чужом окне
почему не работаетprocedure TForm1.Button1Click(Sender: TObject); var h : thandle; begin h := findwindow('Документ -...


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

Или воспользуйтесь поиском по форуму:
27
Ответ Создать тему
Новые блоги и статьи
сукцессия 30. Фосфорный и азотный замки по "честному" закону лимитирования Либиха
anaschu 16.07.2026
Основные достижения за последние дни 1. Механизм отложенного высвобождения фосфора Добавлен специальный пул для медленного разложения меланизированных гиф ЕСМ Реализована разная скорость. . .
Запрет пометки на удаление и отмены проведения
Maks 16.07.2026
Алгоритм из решения ниже реализован на нетиповом документе "ПутевойЛист" разработанного в КА2. Задача: запретить помечать на удаление и отменять проведения путевого листа при условии, если он сдан. . .
Как надо было делать правильно - вообще не слушать ИИ, его дело - текст.
Hrethgir 15.07.2026
А вообще надо было делать не так, чтобы не исправлять ошибку https:/ / www. cyberforum. ru/ blogs/ 223907/ 10996. html , правильно было : удалил кнопку, а потом добавил её. Всё это стресс конечно. Почему?. . .
Знаете, от чего появляется стресс?
kumehtar 15.07.2026
Стресс появляется оттого, что вы, зная как поступить правильно, делаете наоборот. Ларри Уингет
Нас бьют, а мы крепчаем? Какая чушь!
kumehtar 15.07.2026
Вот это вот бытующее мнение, что человек меняется только под действием проблем, всегда считал вредоносным. Поверь, от проблем у людей появляются не изменения, а нервное расстройство и ПТСР. А. . .
сукцессия 29. Переход от одних деревьев на другие делать более или менее вероятностным?
anaschu 12.07.2026
Насколько смена типов микоризы — исключительное событие в двухвековой сукцессии? Оценка вероятности в пространстве параметров В текущей версии модели успешно реализован ключевой механизм. . .
сукцессия 27. Думаю, как переделывать уже написанную статью с планами на сукцессию.
anaschu 12.07.2026
Анализ соответствия модели требованиям Реализованные компоненты: Механизм закисления почвы через протонную помпу Конкуренция между типами микориз pH как триггер сукцессии C/ P соотношение. . .
Сукцессия 26. Мат модель создана.
anaschu 12.07.2026
Модель смены растительных сукцессий посредством управления грибами работает внутри небольшой ячейки почвы, восстанавливающейся после пожара, где ненадолго бывшее царство хвойных снова захватили. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru