Получить пути к выделенным файлам - C#

Узнай цену своей работы

Формулировка задачи:

Как получить пути

НЕ через аргументы вызова

? Дело в том, что в путях везде понатыканы пробелы, ну и, понятное дело, в аргументах для каждого файла получается не его путь, а некая нарезка из фрагментов пути.

Решение задачи: «Получить пути к выделенным файлам»

textual
Листинг программы
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.IO;
  6. using System.Diagnostics;
  7. using System.Threading;
  8. using System.Runtime.InteropServices;
  9. using System.Windows;
  10. using System.Windows.Forms;
  11. using System.Drawing;
  12.  
  13. namespace MultiImpact
  14. {
  15.     public partial class Form1 : Form
  16.     {
  17.         private int WM_IME_NOTIFY = 0x0282;
  18.         private int WM_DESTROY = 0x0002;
  19.         private int WM_NCDESTROY = 0x0082;
  20.         static int WM_CLOSE = 0x0010;
  21.         private int IMN_CLOSESTATUSWINDOW = 0x0001;
  22.         private int WM_KILLFOCUS = 0x0008;
  23.         private int WM_COMMAND = 0x0011;
  24.         [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
  25.         static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);
  26.  
  27.         [DllImport("USER32.DLL")]
  28.         public static extern bool SetForegroundWindow(IntPtr hWnd);
  29.  
  30.         [DllImport("user32.dll", CharSet = CharSet.Auto)]
  31.         private static extern int SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
  32.  
  33.         [DllImport("user32.dll", SetLastError = true)]
  34.         internal static extern bool MoveWindow(IntPtr hwnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);
  35.  
  36.         [DllImport("USER32.DLL")]
  37.         private static extern int GetWindowText(IntPtr IntPtr, StringBuilder lpString, int nMaxCount);
  38.  
  39.         [DllImport("User32.Dll")]
  40.         public static extern void SetWindowText(IntPtr hwnd, String lpString);
  41.  
  42.         [DllImport("User32.dll")]
  43.         public static extern IntPtr GetParent(IntPtr hWnd);
  44.  
  45.         [DllImport("user32.dll")]
  46.         [return: MarshalAs(UnmanagedType.Bool)]
  47.         static extern bool EnumChildWindows(IntPtr hwndParent, EnumWindowProc lpEnumFunc, WinInfo win);
  48.         public delegate bool EnumWindowProc(IntPtr hWnd, WinInfo win);
  49.  
  50.         public class WinInfo
  51.         {
  52.             public string NameStr;
  53.             public IntPtr Handle;
  54.             public WinInfo(string title) { NameStr = title; Handle = new IntPtr(); }
  55.         }
  56.  
  57.         static bool FindWindowByTitle(IntPtr hwnd, WinInfo win)
  58.         {
  59.             StringBuilder str = new StringBuilder(200);
  60.             GetWindowText(hwnd, str, 180);
  61.             if (!str.ToString().Contains(win.NameStr))
  62.                 return true;
  63.             win.Handle = hwnd;
  64.             return false;
  65.         }
  66.  
  67.         static bool FindWindowByClassName(IntPtr hwnd, WinInfo win)
  68.         {
  69.             StringBuilder str = new StringBuilder(200);
  70.             GetClassName(hwnd, str, 180);
  71.             if (!str.ToString().Contains(win.NameStr))
  72.                 return true;
  73.             win.Handle = hwnd;
  74.             return false;
  75.         }
  76.  
  77.         public Form1(string[] args)
  78.         {
  79.             InitializeComponent();
  80.             DaduDadu(args);
  81.         }
  82.  
  83.         void DaduDadu(string[] args)
  84.         {
  85.             const string rus = "абвгдеёжзийклмнопрстуфхцчшщъыьэюя ";
  86.             const string lat = "abvgdeYZzijklmnoprstufhcCWVXyxEUA_";
  87.             const string LabelClassName = "WindowsForms10.STATIC.app.0.14fd2b5";
  88.             string exe = System.Reflection.Assembly.GetExecutingAssembly().Location;
  89.             string tut = Path.GetDirectoryName(exe);
  90.             List<string> arguments = args.ToList<string>();
  91.             string sourse = "";
  92.             foreach (string arg in arguments)
  93.                 sourse += arg;
  94.             if (sourse == "")
  95.             {
  96.                 foreach (Process pr in Process.GetProcessesByName("impacthost"))
  97.                     pr.Kill();
  98.                 return;
  99.             }
  100.             string ext = Path.GetExtension(@sourse).ToLower();
  101.             string dest = Path.GetFileName(@sourse);
  102.             foreach (char ch in dest)
  103.                 if (rus.Contains(ch))
  104.                 {
  105.                     char lch = lat[rus.IndexOf(ch)];
  106.                     dest = dest.Replace(ch, lch);
  107.                 }
  108.             dest = tut + '\\' + dest;
  109.             File.Copy(sourse, dest, true);
  110.             Process currentProc = Process.GetCurrentProcess();
  111.             string procName = currentProc.ProcessName;
  112.             Process[] multiImpacts = Process.GetProcessesByName(procName);
  113.             WinInfo wInf = new WinInfo(LabelClassName);
  114.             EnumChildWindows(multiImpacts[0].MainWindowHandle,
  115.                 FindWindowByClassName, wInf);          //Ищем Label в нулевом мультиИмпакте.
  116.             SetWindowText(wInf.Handle, dest + '\r');  //Передаём туда свой аргумент (можно и самому себе, ничё страшного).
  117.             if (multiImpacts.Count() > 1 && currentProc != multiImpacts[0])
  118.                 currentProc.Kill();//Раз это не нулевой мультиИмпакт, то отдали аргумент нулевому, и делаем харакири.
  119.             string impactPath = File.ReadAllLines(tut + '\\' + "impact.p")[0];
  120.             arguments = label1.Text.Split('\r').ToList<string>();
  121.             foreach (string s in arguments)
  122.             {
  123.                 Process p = new Process();
  124.                 p.StartInfo.FileName = impactPath;
  125.                 switch (ext)
  126.                 {
  127.                     case ".jed":
  128.                         {
  129.                             p.StartInfo.Arguments = "-j " + s;
  130.                             break;
  131.                         }
  132.                     case ".bit":
  133.                         {
  134.                             p.StartInfo.Arguments = "-b " + s + " -mode sserial";
  135.                             break;
  136.                         }
  137.                     default:
  138.                         {
  139.                             p.StartInfo.Arguments = "-j " + s;
  140.                             break;
  141.                         }
  142.                 }
  143.                 p.Start();
  144.             }
  145.             List<Process>impactsList=new List<Process>();
  146.             StringBuilder newImpactTitle = new StringBuilder(200);
  147.             while (impactsList.Count <= arguments.Count || newImpactTitle.ToString() == "")
  148.             {       //Ждём, пока не оживёт последний из импактов.
  149.                 impactsList = Process.GetProcessesByName("impacthost").ToList<Process>();
  150.                 impactsList = impactsList.OrderBy(x => x.StartTime).ToList<Process>();
  151.                 if (impactsList.Count > 0)
  152.                     GetWindowText(impactsList.Last().MainWindowHandle, newImpactTitle, 200);
  153.             }
  154.             foreach(Process p in Process.GetProcessesByName("_impact")) p.Kill();//Грохнули все импактные тупые консоли
  155.             WinInfo targetWindow = new WinInfo("Gq_MvWorkspace" );
  156.             Point position = new Point(0, 0);
  157.             Size size = new Size(160, 210);
  158.             foreach (Process p in Process.GetProcessesByName("impacthost"))
  159.             {
  160.                 EnumChildWindows(p.MainWindowHandle, FindWindowByTitle, targetWindow);
  161.                 IntPtr grandFather = GetParent(GetParent(targetWindow.Handle));
  162.                 List<IntPtr> childWindows = new List<IntPtr>() { grandFather };
  163.                 EnumChildWindows(grandFather, new EnumWindowProc((hwnd, win) =>
  164.                     { childWindows.Add(hwnd); return true; }), new WinInfo(""));
  165.                 EnumChildWindows(p.MainWindowHandle, new EnumWindowProc((hwnd, win) =>
  166.                 {
  167.                     if (!childWindows.Contains(hwnd))
  168.                         SendMessage(hwnd, WM_CLOSE, 0, 0);
  169.                     return true;
  170.                 }
  171.                 ), new WinInfo(""));
  172.                 foreach (Process pr in impactsList)
  173.                 {
  174.                     MoveWindow(pr.MainWindowHandle, (int)position.X, (int)position.Y, (int)size.Width, (int)size.Height, true);
  175.                     SetForegroundWindow(pr.Handle);
  176.                     position.Offset(size.Width, 0);
  177.                     if (position.X >= 1280) position.Offset(-size.Width, size.Height);
  178.                 }
  179.             }
  180.         }
  181.  
  182.         private void Form1_Click(object sender, EventArgs e)
  183.         {
  184.             Process p = Process.GetCurrentProcess();
  185.             EnumChildWindows(p.MainWindowHandle, FindWindowByClassName,
  186.                 new WinInfo("WindowsForms10.STATIC.app.0.14fd2b5"));
  187.         }
  188.     }
  189. }

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

15   голосов , оценка 3.8 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут
Похожие ответы