using Excel = Microsoft.Office.Interop.Excel; void CreateExcel() { Excel.Application xlApp; Excel.Workbook xlWorkBook; Excel.Worksheet xlWorkSheet; object misValue = System.Reflection.Missing.Value; xlApp = new Excel.Application();//new Excel.ApplicationClass(); xlWorkBook = xlApp.Workbooks.Add(misValue); xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1); int i = 3; int j = 0; xlWorkSheet.Cells[1, 1] = "Protocol from " + DateTime.Now.ToShortDateString(); Excel.Range rg = (Excel.Range)xlWorkSheet.Cells[1, 1]; rg.EntireColumn.NumberFormat = "MM/DD/YYYY"; xlWorkSheet.Columns.AutoFit(); xlWorkBook.SaveAs("sdfgsdfg.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, Excel.XlSaveConflictResolution.xlLocalSessionChanges, misValue, misValue, misValue, misValue); xlWorkBook.Close(true, misValue, misValue); xlApp.Quit(); releaseObject(xlWorkSheet); releaseObject(xlWorkBook); releaseObject(xlApp); } private void releaseObject(object obj) { try { System.Runtime.InteropServices.Marshal.ReleaseComObject(obj); obj = null; } catch (Exception ex) { obj = null; } finally { GC.Collect(); } }
C# How to work with Excel. Simple example.
C# How to change UI control from other thread (WinForms and WPF)
WinForms:
public delegate void updateTextBoxDelegate(String textBoxString); public updateTextBoxDelegate updateTextBox; void updateTextBox1(string str ) { textBox1.Text = str1; } void display( string strItem ) { Form1.Invoke( Form1.updateTextBox, strItem ); }
WPF:
tempWindow.Dispatcher.BeginInvoke(new Action(delegate() { tempWindow.ChangeControlMethod(); }));
c# Перехватываем любое окно в Windows и вводим в него текст или прячем
Передаем какой то текст в окно,как будто вводим с клавиатуры и жмем ОК кнопкой Enter:
По аналогии прячем окно:
int iHandle = Common.NativeWin32.FindWindow(null, "Сюда пишем заголовок нужного окна"); Common.NativeWin32.SetForegroundWindow(iHandle); System.Windows.Forms.SendKeys.SendWait("Здесь пишем текст который нужно ввести в это окно"); //Жмем в окне Enter System.Windows.Forms.SendKeys.SendWait("{ENTER}");
По аналогии прячем окно:
int iHandle = Common.NativeWin32.FindWindow(null, "Заголовок окна"); Common.NativeWin32.SetWindowPos(new IntPtr(iHandle), Common.NativeWin32.HWND.Top, 0, 0, 0, 0, Common.NativeWin32.SetWindowPosFlags.AsynchronousWindowPosition);
Вспомогательный класс:
using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; namespace DeclTerminalApp.Common { class NativeWin32 { public const int WM_SYSCOMMAND = 0x0112; public const int SC_CLOSE = 0xF060; [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, SetWindowPosFlags uFlags); static readonly IntPtr HWND_TOPMOST = new IntPtr(-1); static readonly IntPtr HWND_NOTOPMOST = new IntPtr(-2); static readonly IntPtr HWND_TOP = new IntPtr(0); static readonly IntPtr HWND_BOTTOM = new IntPtr(1); /// <summary> /// Window handles (HWND) used for hWndInsertAfter /// </summary> public static class HWND { public static IntPtr NoTopMost = new IntPtr(-2), TopMost = new IntPtr(-1), Top = new IntPtr(0), Bottom = new IntPtr(1); } /// <summary> /// SetWindowPos Flags /// </summary> public static class SWP { public static readonly int NOSIZE = 0x0001, NOMOVE = 0x0002, NOZORDER = 0x0004, NOREDRAW = 0x0008, NOACTIVATE = 0x0010, DRAWFRAME = 0x0020, FRAMECHANGED = 0x0020, SHOWWINDOW = 0x0040, HIDEWINDOW = 0x0080, NOCOPYBITS = 0x0100, NOOWNERZORDER = 0x0200, NOREPOSITION = 0x0200, NOSENDCHANGING = 0x0400, DEFERERASE = 0x2000, ASYNCWINDOWPOS = 0x4000; } [Flags()] public enum SetWindowPosFlags : uint { /// <summary>If the calling thread and the thread that owns the window are attached to different input queues, /// the system posts the request to the thread that owns the window. This prevents the calling thread from /// blocking its execution while other threads process the request.</summary> /// <remarks>SWP_ASYNCWINDOWPOS</remarks> AsynchronousWindowPosition = 0x4000, /// <summary>Prevents generation of the WM_SYNCPAINT message.</summary> /// <remarks>SWP_DEFERERASE</remarks> DeferErase = 0x2000, /// <summary>Draws a frame (defined in the window's class description) around the window.</summary> /// <remarks>SWP_DRAWFRAME</remarks> DrawFrame = 0x0020, /// <summary>Applies new frame styles set using the SetWindowLong function. Sends a WM_NCCALCSIZE message to /// the window, even if the window's size is not being changed. If this flag is not specified, WM_NCCALCSIZE /// is sent only when the window's size is being changed.</summary> /// <remarks>SWP_FRAMECHANGED</remarks> FrameChanged = 0x0020, /// <summary>Hides the window.</summary> /// <remarks>SWP_HIDEWINDOW</remarks> HideWindow = 0x0080, /// <summary>Does not activate the window. If this flag is not set, the window is activated and moved to the /// top of either the topmost or non-topmost group (depending on the setting of the hWndInsertAfter /// parameter).</summary> /// <remarks>SWP_NOACTIVATE</remarks> DoNotActivate = 0x0010, /// <summary>Discards the entire contents of the client area. If this flag is not specified, the valid /// contents of the client area are saved and copied back into the client area after the window is sized or /// repositioned.</summary> /// <remarks>SWP_NOCOPYBITS</remarks> DoNotCopyBits = 0x0100, /// <summary>Retains the current position (ignores X and Y parameters).</summary> /// <remarks>SWP_NOMOVE</remarks> IgnoreMove = 0x0002, /// <summary>Does not change the owner window's position in the Z order.</summary> /// <remarks>SWP_NOOWNERZORDER</remarks> DoNotChangeOwnerZOrder = 0x0200, /// <summary>Does not redraw changes. If this flag is set, no repainting of any kind occurs. This applies to /// the client area, the nonclient area (including the title bar and scroll bars), and any part of the parent /// window uncovered as a result of the window being moved. When this flag is set, the application must /// explicitly invalidate or redraw any parts of the window and parent window that need redrawing.</summary> /// <remarks>SWP_NOREDRAW</remarks> DoNotRedraw = 0x0008, /// <summary>Same as the SWP_NOOWNERZORDER flag.</summary> /// <remarks>SWP_NOREPOSITION</remarks> DoNotReposition = 0x0200, /// <summary>Prevents the window from receiving the WM_WINDOWPOSCHANGING message.</summary> /// <remarks>SWP_NOSENDCHANGING</remarks> DoNotSendChangingEvent = 0x0400, /// <summary>Retains the current size (ignores the cx and cy parameters).</summary> /// <remarks>SWP_NOSIZE</remarks> IgnoreResize = 0x0001, /// <summary>Retains the current Z order (ignores the hWndInsertAfter parameter).</summary> /// <remarks>SWP_NOZORDER</remarks> IgnoreZOrder = 0x0004, /// <summary>Displays the window.</summary> /// <remarks>SWP_SHOWWINDOW</remarks> ShowWindow = 0x0040, } [DllImport("user32.dll")] public static extern int FindWindow( string lpClassName, // class name string lpWindowName // window name ); [DllImport("user32.dll")] public static extern int SendMessage( int hWnd, // handle to destination window uint Msg, // message int wParam, // first message parameter int lParam // second message parameter ); [DllImport("user32.dll")] public static extern int SetForegroundWindow( int hWnd // handle to window ); private const int GWL_EXSTYLE = (-20); private const int WS_EX_TOOLWINDOW = 0x80; private const int WS_EX_APPWINDOW = 0x40000; public const int GW_HWNDFIRST = 0; public const int GW_HWNDLAST = 1; public const int GW_HWNDNEXT = 2; public const int GW_HWNDPREV = 3; public const int GW_OWNER = 4; public const int GW_CHILD = 5; public delegate int EnumWindowsProcDelegate(int hWnd, int lParam); [DllImport("user32")] public static extern int EnumWindows(EnumWindowsProcDelegate lpEnumFunc, int lParam); [DllImport("User32.Dll")] public static extern void GetWindowText(int h, StringBuilder s, int nMaxCount); [DllImport("user32", EntryPoint = "GetWindowLongA")] public static extern int GetWindowLongPtr(int hwnd, int nIndex); [DllImport("user32")] public static extern int GetParent(int hwnd); [DllImport("user32")] public static extern int GetWindow(int hwnd, int wCmd); [DllImport("user32")] public static extern int IsWindowVisible(int hwnd); [DllImport("user32")] public static extern int GetDesktopWindow(); } }
c# Вставляем флэшку в компьютер и обрабатываем это событие
Thread t = new Thread(Flashwatcher); t.Start(); //... private void Flashwatcher() { ManagementScope scope = new ManagementScope("root\\CIMV2"); scope.Options.EnablePrivileges = true; WqlEventQuery query = new WqlEventQuery(); query.EventClassName = "__InstanceCreationEvent"; query.WithinInterval = new TimeSpan(0, 0, 1); query.Condition = @"TargetInstance ISA 'Win32_USBControllerdevice'"; watcher = new ManagementEventWatcher(scope, query); watcher.Start(); watcher.WaitForNextEvent(); }
c# Пишем аналог КриптоАРМ Подписать и зашифровать с архивированием перед шифрованием.
Для создания Zip используем библиотеку:
using Ionic.Zip;
Сам код:
static bool SigZipEnc(string _path, bool _pin, X509Certificate2 cert,X509Certificate2 recipientCert) { try { Sign(_path,cert); CreateZipArhive(_path+".sig"); EncryptMsg(_path+".zip", recipientCert); } catch { return false; } return true; } static void CreateZipArhive(string _pathin) { using (ZipFile zip = new ZipFile()) { zip.AddFile(_pathin); zip.Save(_pathin+".zip"); } } static void EncryptMsg( string _path, X509Certificate2 recipientCert) { Byte[] msg = System.IO.File.ReadAllBytes(_path); ContentInfo contentInfo = new ContentInfo(msg); EnvelopedCms envelopedCms = new EnvelopedCms(contentInfo); CmsRecipient recip1 = new CmsRecipient(recipientCert); envelopedCms.Encrypt(recip1); byte[] encodedMsg = envelopedCms.Encode(); System.IO.File.WriteAllBytes(_path + ".enc", encodedMsg); } public static void Sign(string _path, X509Certificate2 cert) { byte[] msgBytes = System.IO.File.ReadAllBytes(_path); ContentInfo contentInfo = new ContentInfo(msgBytes); SignedCms signedCms = new SignedCms(contentInfo); CmsSigner cmsSigner = new CmsSigner(cert); signedCms.ComputeSignature(cmsSigner); byte[] encodedMsg = signedCms.Encode(); System.IO.File.WriteAllBytes(_path + ".sig", encodedMsg); }
Cryptopro c# Get the list of all certificate containers
public class Win32 { [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)] public static extern bool CryptAcquireContext( ref IntPtr hProv, string pszContainer, string pszProvider, uint dwProvType, uint dwFlags); [DllImport("advapi32.dll", SetLastError = true)] public static extern bool CryptGetProvParam( IntPtr hProv, uint dwParam, [In, Out] byte[] pbData, ref uint dwDataLen, uint dwFlags); [DllImport("advapi32.dll", SetLastError = true)] public static extern bool CryptGetProvParam( IntPtr hProv, uint dwParam, [MarshalAs(UnmanagedType.LPStr)] StringBuilder pbData, ref uint dwDataLen, uint dwFlags); [DllImport("advapi32.dll")] public static extern bool CryptReleaseContext( IntPtr hProv, uint dwFlags); }
using System; using System.Runtime.InteropServices; using System.ComponentModel; using System.Collections; using System.Text; namespace CryptoHelper { public static class CryptoHelper { public static string[] GetContainerNames() { int BUFFSIZE = 512; ArrayList containernames = new ArrayList(); uint pcbData = 0; //String provider = null; //can use null, for default provider String provider = "Crypto-Pro GOST R 34.10-2001 Cryptographic Service Provider"; String container = null; //required for crypt_verifycontext uint type = PROV_RSA_FULL; uint cspflags = CRYPT_VERIFYCONTEXT | CSPKEYTYPE; //no private key access required. uint enumflags = PP_ENUMCONTAINERS; //specify container enumeration functdionality IntPtr hProv = IntPtr.Zero; uint dwFlags = CRYPT_FIRST; bool gotcsp = Win32.CryptAcquireContext(ref hProv, container, provider, type, cspflags); if (!gotcsp) { showWin32Error(Marshal.GetLastWin32Error()); return null; } StringBuilder sb = null; Win32.CryptGetProvParam(hProv, enumflags, sb, ref pcbData, dwFlags); BUFFSIZE = (int)(2 * pcbData); sb = new StringBuilder(BUFFSIZE); /* ---------- Get KeyContainer Names ------------- */ dwFlags = CRYPT_FIRST; //required initalization while (Win32.CryptGetProvParam(hProv, enumflags, sb, ref pcbData, dwFlags)) { dwFlags = 0; //required to continue entire enumeration containernames.Add(sb.ToString()); } if (hProv != IntPtr.Zero) Win32.CryptReleaseContext(hProv, 0); if (containernames.Count == 0) return null; else return (string[])containernames.ToArray(Type.GetType("System.String")); } const uint PROV_RSA_FULL = 0x00000001; const uint CRYPT_VERIFYCONTEXT = 0xF0000000; static uint CSPKEYTYPE = 0; const uint PP_ENUMCONTAINERS = 0x00000002; const uint CRYPT_FIRST = 0x00000001; private static void showWin32Error(int errorcode) { Win32Exception myEx = new Win32Exception(errorcode); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Error code:\t 0x{0:X}", myEx.ErrorCode); Console.WriteLine("Error message:\t {0}\n", myEx.Message); Console.ForegroundColor = ConsoleColor.White; } } }
Subscribe to:
Posts (Atom)