Получить пути к выделенным файлам - C#
Формулировка задачи:
Как получить пути
НЕ через аргументы вызова
? Дело в том, что в путях везде понатыканы пробелы, ну и, понятное дело, в аргументах для каждого файла получается не его путь, а некая нарезка из фрагментов пути.Решение задачи: «Получить пути к выделенным файлам»
textual
Листинг программы
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.IO;
- using System.Diagnostics;
- using System.Threading;
- using System.Runtime.InteropServices;
- using System.Windows;
- using System.Windows.Forms;
- using System.Drawing;
- namespace MultiImpact
- {
- public partial class Form1 : Form
- {
- private int WM_IME_NOTIFY = 0x0282;
- private int WM_DESTROY = 0x0002;
- private int WM_NCDESTROY = 0x0082;
- static int WM_CLOSE = 0x0010;
- private int IMN_CLOSESTATUSWINDOW = 0x0001;
- private int WM_KILLFOCUS = 0x0008;
- private int WM_COMMAND = 0x0011;
- [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
- static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);
- [DllImport("USER32.DLL")]
- public static extern bool SetForegroundWindow(IntPtr hWnd);
- [DllImport("user32.dll", CharSet = CharSet.Auto)]
- private static extern int SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
- [DllImport("user32.dll", SetLastError = true)]
- internal static extern bool MoveWindow(IntPtr hwnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);
- [DllImport("USER32.DLL")]
- private static extern int GetWindowText(IntPtr IntPtr, StringBuilder lpString, int nMaxCount);
- [DllImport("User32.Dll")]
- public static extern void SetWindowText(IntPtr hwnd, String lpString);
- [DllImport("User32.dll")]
- public static extern IntPtr GetParent(IntPtr hWnd);
- [DllImport("user32.dll")]
- [return: MarshalAs(UnmanagedType.Bool)]
- static extern bool EnumChildWindows(IntPtr hwndParent, EnumWindowProc lpEnumFunc, WinInfo win);
- public delegate bool EnumWindowProc(IntPtr hWnd, WinInfo win);
- public class WinInfo
- {
- public string NameStr;
- public IntPtr Handle;
- public WinInfo(string title) { NameStr = title; Handle = new IntPtr(); }
- }
- static bool FindWindowByTitle(IntPtr hwnd, WinInfo win)
- {
- StringBuilder str = new StringBuilder(200);
- GetWindowText(hwnd, str, 180);
- if (!str.ToString().Contains(win.NameStr))
- return true;
- win.Handle = hwnd;
- return false;
- }
- static bool FindWindowByClassName(IntPtr hwnd, WinInfo win)
- {
- StringBuilder str = new StringBuilder(200);
- GetClassName(hwnd, str, 180);
- if (!str.ToString().Contains(win.NameStr))
- return true;
- win.Handle = hwnd;
- return false;
- }
- public Form1(string[] args)
- {
- InitializeComponent();
- DaduDadu(args);
- }
- void DaduDadu(string[] args)
- {
- const string rus = "абвгдеёжзийклмнопрстуфхцчшщъыьэюя ";
- const string lat = "abvgdeYZzijklmnoprstufhcCWVXyxEUA_";
- const string LabelClassName = "WindowsForms10.STATIC.app.0.14fd2b5";
- string exe = System.Reflection.Assembly.GetExecutingAssembly().Location;
- string tut = Path.GetDirectoryName(exe);
- List<string> arguments = args.ToList<string>();
- string sourse = "";
- foreach (string arg in arguments)
- sourse += arg;
- if (sourse == "")
- {
- foreach (Process pr in Process.GetProcessesByName("impacthost"))
- pr.Kill();
- return;
- }
- string ext = Path.GetExtension(@sourse).ToLower();
- string dest = Path.GetFileName(@sourse);
- foreach (char ch in dest)
- if (rus.Contains(ch))
- {
- char lch = lat[rus.IndexOf(ch)];
- dest = dest.Replace(ch, lch);
- }
- dest = tut + '\\' + dest;
- File.Copy(sourse, dest, true);
- Process currentProc = Process.GetCurrentProcess();
- string procName = currentProc.ProcessName;
- Process[] multiImpacts = Process.GetProcessesByName(procName);
- WinInfo wInf = new WinInfo(LabelClassName);
- EnumChildWindows(multiImpacts[0].MainWindowHandle,
- FindWindowByClassName, wInf); //Ищем Label в нулевом мультиИмпакте.
- SetWindowText(wInf.Handle, dest + '\r'); //Передаём туда свой аргумент (можно и самому себе, ничё страшного).
- if (multiImpacts.Count() > 1 && currentProc != multiImpacts[0])
- currentProc.Kill();//Раз это не нулевой мультиИмпакт, то отдали аргумент нулевому, и делаем харакири.
- string impactPath = File.ReadAllLines(tut + '\\' + "impact.p")[0];
- arguments = label1.Text.Split('\r').ToList<string>();
- foreach (string s in arguments)
- {
- Process p = new Process();
- p.StartInfo.FileName = impactPath;
- switch (ext)
- {
- case ".jed":
- {
- p.StartInfo.Arguments = "-j " + s;
- break;
- }
- case ".bit":
- {
- p.StartInfo.Arguments = "-b " + s + " -mode sserial";
- break;
- }
- default:
- {
- p.StartInfo.Arguments = "-j " + s;
- break;
- }
- }
- p.Start();
- }
- List<Process>impactsList=new List<Process>();
- StringBuilder newImpactTitle = new StringBuilder(200);
- while (impactsList.Count <= arguments.Count || newImpactTitle.ToString() == "")
- { //Ждём, пока не оживёт последний из импактов.
- impactsList = Process.GetProcessesByName("impacthost").ToList<Process>();
- impactsList = impactsList.OrderBy(x => x.StartTime).ToList<Process>();
- if (impactsList.Count > 0)
- GetWindowText(impactsList.Last().MainWindowHandle, newImpactTitle, 200);
- }
- foreach(Process p in Process.GetProcessesByName("_impact")) p.Kill();//Грохнули все импактные тупые консоли
- WinInfo targetWindow = new WinInfo("Gq_MvWorkspace" );
- Point position = new Point(0, 0);
- Size size = new Size(160, 210);
- foreach (Process p in Process.GetProcessesByName("impacthost"))
- {
- EnumChildWindows(p.MainWindowHandle, FindWindowByTitle, targetWindow);
- IntPtr grandFather = GetParent(GetParent(targetWindow.Handle));
- List<IntPtr> childWindows = new List<IntPtr>() { grandFather };
- EnumChildWindows(grandFather, new EnumWindowProc((hwnd, win) =>
- { childWindows.Add(hwnd); return true; }), new WinInfo(""));
- EnumChildWindows(p.MainWindowHandle, new EnumWindowProc((hwnd, win) =>
- {
- if (!childWindows.Contains(hwnd))
- SendMessage(hwnd, WM_CLOSE, 0, 0);
- return true;
- }
- ), new WinInfo(""));
- foreach (Process pr in impactsList)
- {
- MoveWindow(pr.MainWindowHandle, (int)position.X, (int)position.Y, (int)size.Width, (int)size.Height, true);
- SetForegroundWindow(pr.Handle);
- position.Offset(size.Width, 0);
- if (position.X >= 1280) position.Offset(-size.Width, size.Height);
- }
- }
- }
- private void Form1_Click(object sender, EventArgs e)
- {
- Process p = Process.GetCurrentProcess();
- EnumChildWindows(p.MainWindowHandle, FindWindowByClassName,
- new WinInfo("WindowsForms10.STATIC.app.0.14fd2b5"));
- }
- }
- }
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д