Showing posts with label Windows. Show all posts
Showing posts with label Windows. Show all posts

creating win service

C:\Documents and Settings\Administrator> sc create asperacentral binPath= "C:\Program Files\Aspera\Enterprise Server\bin\Debug\asperacentral.exe" DisplayName= "Aspera Central" start= auto

c# stop/terminate/taskkill windows service

in cmd


sc queryex servicename

From the results of this query, jot down the PID.


taskkill /f /pid [PID]

c# check either work or not service on a remote computer

 
using System.Management;

       static bool ServiceIsRunning(string ServiceName)
        {
            ConnectionOptions op = new ConnectionOptions();
            op.Username = "domain\\username";
            op.Password = "password";
            ManagementScope scope = new ManagementScope("\\\\OLAP1\\root\\cimv2", op);
            scope.Connect();

            string objPath = string.Format("Win32_Service.Name='{0}'", "SubscribeReportService");
            using (ManagementObject service = new ManagementObject(scope, new ManagementPath(objPath), null))
            {
                if (service.GetPropertyValue("State").ToString() == "Running")
                    return true;
                else
                    return false;
            }
        }

http://stackoverflow.com/questions/1335065/check-status-of-services-that-run-in-a-remote-computer-using-c-sharp

hotkeys for totalcommander

ALT + F5  - create archive

ALT + f6 -  unzip

at element [..] Shift + F6  - edit path to current folder

How to Register ActiveX/COM dll in order to use with c#


If the DLL is 32 bit:
Copy the DLL to C:\Windows\SysWoW64\
In an elevated command prompt: %windir%\SysWoW64\regsvr32.exe %windir%\SysWoW64\namedll.dll
if the DLL is 64 bit:
Copy the DLL to C:\Windows\System32\
In an elevated command prompt: %windir%\System32\regsvr32.exe %windir%\System32\namedll.dll
I know it seems the wrong way round, but that's the way it works. See:
http://support.microsoft.com/kb/249873
Quote: "Note On a 64-bit version of a Windows operating system, there are two versions of the Regsv32.exe file:
The 64-bit version is %systemroot%\System32\regsvr32.exe.
The 32-bit version is %systemroot%\SysWoW64\regsvr32.exe.

In order to solve next problem you have to run cmd as an Administrator
“The module “%1″ was loaded but the call to DllRegisterServer failed with error code 0×80004005. For more information about this problem, search online using the error code as a search term”.




iis Ошибка 503

Проделать шаги по ссылке http://mvolo.com/where-did-my-iis7-server-go-troubleshooting-503-quotservice-unavailablequot-errors/

Не забыть командную строку под админом запустить

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();
    }
}

дизасемблер для приложений .NET / Disassembler for .NET Applications


Приведенная ниже команда выводит метаданные и дизассемблированный код PE-файла MyHello.exe в стандартном графическом интерфейсе пользователя программы Ildasm.exe.
Копировать
ildasm myHello.exe
Копировать
ildasm myHello.exe

Приведенная ниже команда дизассемблирует файл MyFile.exe и сохраняет выходной текст для ассемблера MSIL в файле MyFile.il.
Копировать
ildasm MyFile.exe /output:MyFile.il
Копировать
ildasm MyFile.exe /output:MyFile.il

Приведенная ниже команда дизассемблирует файл MyFile.exe и выводит выходной текст для ассемблера MSIL на консоль.
Копировать
ildasm MyFile.exe /text
Копировать
ildasm MyFile.exe /text

Если файл MyApp.exe содержит внедренные управляемые и неуправляемые ресурсы, в результате выполнения следующей команды будет создано четыре файла: MyApp.il, MyApp.res, Icons.resources, и Message.resources.
Копировать
ildasm MyApp.exe /output:MyApp.il
Копировать
ildasm MyApp.exe /output:MyApp.il

Приведенная ниже команда дизассемблирует метод MyMethod класса MyClass в файле MyFile.exe и выводит результат в окно консоли.
Копировать
ildasm /item:MyClass::MyMethod MyFile.exe /text
Копировать
ildasm /item:MyClass::MyMethod MyFile.exe /text

В предыдущем примере допустимо наличие нескольких методов с именем MyMethod и различными подписями. Приведенная ниже команда дизассемблирует метод экземпляра MyMethod с типом возвращаемого значения void и типами параметров int32 и string.
Копировать
ildasm /item:"MyClass::MyMethod(instance void(int32,string)" MyFile.exe /text

Настройка принтера HP P1102w через WIFI

Вообщем всё очень просто. Сама идея заключается в том что ваш принтер подключается к WiFi роутеру,а все находящиеся в зоне действия этого wifi могут подключится к принтеру,сам принтер стоит в углу включенный в разетку и мигает синей лампочкой.

Итак поэтапно:
1. Подключаем принтер к любому компьютеру,устанваливаем все дрова и программы стандартно с диска, при установке выбираем "Подключение через USB"
2. Потом заходим в пуск,находим в программах папку с нашим принтером,там есть специальная программка для настройки wifi,не помню как точно называется,запускаем её.
3. Там выбираем настроить вручную,не автоматом,принтер ищет доступные wifi роутеры, выбираем нужный, вводим пароль от wifi, жмем ОК
4. Теперь остается с компьютеров которые желаем подключить зайти в "устройства и принтеры" и нажать добавить принтер, там выбрать подключение по беспроводной сети. Данный компьютер должен быть естественно подключен к wifi. Следуем инструкциям и вуаля, всё работает.
5. Пункт 4 повторяем со всеми нужными компьютерами.