public static List<string> GetCertNamesFromStore(string search) { X509Store store = new X509Store("My"); try { store.Open(OpenFlags.ReadOnly); X509Certificate2Collection certCollection = store.Certificates; X509Certificate2Collection currentCerts = certCollection.Find(X509FindType.FindByTimeValid, DateTime.Now, false); var res = new List<string>(); foreach (X509Certificate2 s in certCollection) { if (search=="") res.Add(GetSubjectCN(s)); else if (s.SubjectName.Name.Contains(search)) res.Add(GetSubjectCN(s)); } return res; } finally { store.Close(); } }
C# How to get all certificates from "My" Store
C# Обработываем событие на Hotkey в приложениях WPF
Способ 1
Способ 2
public MainWindow() { InitializeComponent(); AddHandler(Keyboard.KeyDownEvent, (KeyEventHandler)HandleKeyDownEvent); } private void HandleKeyDownEvent(object sender, KeyEventArgs e) { if (e.Key == Key.Tab && (Keyboard.Modifiers & (ModifierKeys.Control | ModifierKeys.Shift)) == (ModifierKeys.Control | ModifierKeys.Shift)) { MessageBox.Show("CTRL + SHIFT + TAB trapped"); } if (e.Key == Key.Tab && (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control) { MessageBox.Show("CTRL + TAB trapped"); } }
Способ 2
<Window x:Class="WPFHotkey.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WPFHotkey" Title="MainWindow" Height="350" Width="525"> <Window.CommandBindings> <CommandBinding Command="local:MainWindow.Some_Command" Executed="Some_Executed"/> </Window.CommandBindings> <Window.InputBindings> <KeyBinding Key="F4" Modifiers="ALT" Command="local:MainWindow.Some_Command"/> </Window.InputBindings> <Grid> </Grid> </Window>
using System.Windows; using System.Windows.Input; namespace WPFHotkey { public partial class MainWindow : Window { public static RoutedCommand Some_Command = new RoutedCommand(); private void Some_Executed(object sender, ExecutedRoutedEventArgs e) { MessageBox.Show("Hi!"); } public MainWindow() { InitializeComponent(); } } }
c# проверяем xml по xsd схеме
using System; using System.Xml; using System.Xml.Schema; using System.IO; public class Sample { public static void Main() { XmlSchemaSet sc = new XmlSchemaSet(); sc.Add("", "books.xsd"); XmlReaderSettings settings = new XmlReaderSettings(); settings.ValidationType = ValidationType.Schema; settings.Schemas = sc; settings.ValidationEventHandler += new ValidationEventHandler (ValidationCallBack); XmlReader reader = XmlReader.Create("booksSchemaFail.xml", settings); while (reader.Read()); } private static void ValidationCallBack(object sender, ValidationEventArgs e) { Console.WriteLine("Validation Error: {0}", e.Message); } }
C# How to work with Excel. Simple example.
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 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(); } }
Subscribe to:
Posts (Atom)