【语言-c#】程序A的窗口Form1向程序B的窗口Form2 发送消息

一、获取程序B的ClassName

1、程序B非自己开发

使用vs ->工具(T)->spy++(+)->监视(S)->查找窗口(F)...->查找程序工具


2、程序B是自己开发

可以使用GetClassName获取B程序Form2的ClassName,将其存入指定的注册表位置、配置文件或数据库等等,这里我简单介绍存入注册表的用法。

using System.Runtime.InteropServices;
        /// <summary>
        /// 获取类名
        /// </summary>
        /// <param name="hWnd">窗口的句柄,间接地是窗口所属的类。</param>
        /// <param name="lpClassName">类名字符串</param>
        /// <param name="nMaxCount">lpClassName的缓冲区的长度,字符。缓冲区必须足够大,以包括终止空字符;否则,类名字符串被截断为nMaxCount-1个字符。</param>
        /// <returns>如果函数成功,返回值是复制到缓冲区的字符数,不包括终止空字符。如果函数失败,返回值为0。</returns>
        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        public static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);
public Form2()
        {
            InitializeComponent();
            try
            {
                StringBuilder SB = new StringBuilder(255);
                int numberOfSBLength = API.Win32API.GetClassName(this.Handle, SB, 255);
                if (numberOfSBLength > 0)
                {
                    API.CRegeditEx.SetValue(API.CRegeditEx.REGPATH_Config, "SoundAcquisitionClassName", SB.ToString());
                }
            }
            catch (Exception exp)
            {
            }
        }

二、程序A向程序B发送消息

IntPtr hwnd_win;
                string classname =  API.CRegeditEx.GetValue(API.CRegeditEx.REGPATH_Config, "SoundAcquisitionClassName", "WindowsForms10.window.8.app.0.141b42a_r9_ad1");
                hwnd_win = API.Win32API.FindWindow(classname, "SoundAcquisition");
                Message msg = Message.Create(hwnd_win, CUserAPI.UWM_SoundAcquisitionStop, new IntPtr(0), new IntPtr(0));
                API.Win32API.SendMessage(msg.HWnd, msg.Msg, msg.WParam, msg.LParam);

三、附件

CRegeditEx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Win32;
using System.Drawing;


namespace CallingSystem.API
{
    /// <summary>
    /// 注册表
    /// </summary>
    public class CRegeditEx
    {

        #region 项、键与值
        #region 项
        public const string REGPATH_Config = "SOFTWARE\\CallingSystem\\Config";
        public const string REGPATH_Voice = "SOFTWARE\\CallingSystem\\Voice";

        public const string REG_SOFTWARE = "SOFTWARE";
        public const string REG_CallingSystem = "CallingSystem";
        public const string REG_Config = "Config";
        public const string REG_Voice = "Voice";
        public const string REG_Enable = "Enable";
        public const string REG_Name = "Name";
        public const string Value_Ture = "1";
        public const string Value_False = "0";
        public const string Value_Empty = "";
        public const string InitEnable = "0";
        public const int IntValue_Zero = 0;
        #endregion
        #endregion


        public static void VoiceName(string name)
        {
            SetValue(REGPATH_Voice, REG_Name, name);
        }

        public static string VoiceName()
        {
            return GetValue(REGPATH_Voice, REG_Name,CRSSSpeech.Voice_Huihui);
        }

        public static void SetValue(string path, string key, Color value)
        {
            string va = System.Drawing.ColorTranslator.ToHtml(value);
            SetValue(path, key, va);
        }
        public static void SetValue(string path, string key, Rectangle value)
        {
            RectangleConverter rc = new RectangleConverter();
            string va = rc.ConvertToInvariantString(value);
            SetValue(path, key, va);
        }
        public static int GetValue(string path, string key, int defaultvalue)
        {
            try
            {
                return CSConvert.ToInt (GetValue(path, key, defaultvalue .ToString()));
            }
            catch (Exception exp)
            {
                return defaultvalue;
            }
        }
        public static Rectangle GetValue(string path, string key, Rectangle defaultvalue)
        {
            try
            {
                RectangleConverter rc = new RectangleConverter();
                return (Rectangle)rc.ConvertFromInvariantString(GetValue(path, key, rc.ConvertToInvariantString(defaultvalue)));
            }
            catch (Exception exp)
            {
                return defaultvalue;
            }
        }

        public static Color GetValue(string path, string key, Color defaultvalue)
        {
            try
            {
                return System.Drawing.ColorTranslator.FromHtml(GetValue(path, key, System.Drawing.ColorTranslator.ToHtml(defaultvalue)));
            }
            catch (Exception exp)
            {
                return defaultvalue ;
            }
        }

        public static Font GetValue(string path, string key, Font defaultvalue)
        {
            try
            {
                FontConverter fc = new FontConverter();
                return (Font)fc.ConvertFromString(GetValue(path, key, fc.ConvertToInvariantString(defaultvalue)));
            }
            catch (Exception exp)
            {
                return defaultvalue;
            }
        }

        public static void SetValue(string path, string key, Font value)
        {
            try
            {
                FontConverter fc = new FontConverter();
                string va = fc.ConvertToInvariantString(value);
                SetValue(path, key, va);
            }
            catch (Exception exp)
            {

            }
        }
        public static void SetValue(string path, string key, bool value)
        {
            if(value)
            {
                SetValue(path, key, Value_Ture);
            }
            else
            {
                SetValue(path, key, Value_False);
            }
        }
        public static void SetValue(string path, string key, string value)
        {
            try
            {
                RegistryKey rk = Registry.CurrentUser.OpenSubKey(path, true);
                if (rk == null)
                {
                    Create();
                    rk = Registry.CurrentUser.OpenSubKey(path, true);
                }
                if (rk == null)
                {
                    return;
                }
                rk.SetValue(key, value);
                rk.Close();
            }
            catch (Exception exp)
            {
                System.Windows.Forms.MessageBox.Show(exp.Message);
                return;
            }
        }
        public static bool GetValue(string path, string key, bool defaultvalue)
        {
            string tmp = GetValue(path,key,defaultvalue?"1":"0");
            if(tmp == "0")
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        public static string GetValue(string path, string key, string defaultvalue = Value_Empty)
        {
            //  RegistryKey key = Registry.CurrentUser.OpenSubKey("HKEY_LOCAL_MACHINE\\SOFTWARE", true);
            string value = Value_Empty;
            try
            {
                RegistryKey rk = Registry.CurrentUser.OpenSubKey(path, true);
                if (rk == null)
                {
                    Create();
                    rk = Registry.CurrentUser.OpenSubKey(path, true);
                }
                if (rk == null)
                {
                    return defaultvalue;
                }
                // if (Membrane != null)
                if (IsRegeditKeyExist(rk, key))
                {
                    value = rk.GetValue(key).ToString();
                }
                else
                {
                    if (value == Value_Empty)
                        rk.SetValue(key, defaultvalue);
                    value = defaultvalue;
                }
                rk.Close();
            }
            catch (Exception exp)
            {
                System.Windows.Forms.MessageBox.Show(exp.Message);
                value = defaultvalue;
            }
            return value;
        }
       

        
        public static void Delete()
        {
            try
            {
                RegistryKey key = Registry.CurrentUser;
                RegistryKey software = Registry.CurrentUser.OpenSubKey(REG_SOFTWARE, true);
                if (software == null)
                    software = key.CreateSubKey(REG_SOFTWARE);

                RegistryKey callingsystem = software.OpenSubKey(REG_CallingSystem, true);
                if (callingsystem == null)
                    callingsystem = software.CreateSubKey(REG_CallingSystem);


                RegistryKey config = callingsystem.OpenSubKey(REG_Config, true);
                if (config != null)
                {
                    string keyNameRectangle = "Rectangle";
                    string keyNameFont = "Font";
                    string keyNameColorF = "ColorFore";
                    string keyNameColorB = "ColorBack";
                    string keyNameContentAlignment = "ContentAlignment";

                    int no = 0;
                    for(int i = -1;i < 10000;i++)
                    {
                        if (no > 200)
                            return;
                        if (IsRegeditKeyExist(config, keyNameRectangle + i)) { config.DeleteValue(keyNameRectangle + i); } else { no++; }
                        if (IsRegeditKeyExist(config, keyNameFont + i)) {config.DeleteValue(keyNameFont + i);}
                        if (IsRegeditKeyExist(config, keyNameColorF + i)){ config.DeleteValue(keyNameColorF + i);}
                        if (IsRegeditKeyExist(config, keyNameColorB + i)){ config.DeleteValue(keyNameColorB + i);}
                        if (IsRegeditKeyExist(config, keyNameContentAlignment + i)) { config.DeleteValue(keyNameContentAlignment + i); }
                    }
                }
                config.Close();
                callingsystem.Close();
                software.Close();
                key.Close();
            }
            catch(Exception exp)
            {

            }

        }
        private static void Create()
        {
            string value = Value_Empty;
            try
            {
                RegistryKey key = Registry.CurrentUser;

                RegistryKey software = Registry.CurrentUser.OpenSubKey(REG_SOFTWARE, true);
                if (software == null)
                    software = key.CreateSubKey(REG_SOFTWARE);

                RegistryKey callingsystem = software.OpenSubKey(REG_CallingSystem, true);
                if (callingsystem == null)
                    callingsystem = software.CreateSubKey(REG_CallingSystem);


                RegistryKey config = callingsystem.OpenSubKey(REG_Config, true);
                if (config == null)
                    config = callingsystem.CreateSubKey(REG_Config);

                if (IsRegeditKeyExist(config, REG_Enable))
                {
                    value = config.GetValue(REG_Enable).ToString();
                }
                else
                {
                    if (value == Value_Empty)
                        config.SetValue(REG_Enable, InitEnable);
                    value = InitEnable;
                }


                RegistryKey voc = callingsystem.OpenSubKey(REG_Voice, true);
                if (voc == null)
                    voc = callingsystem.CreateSubKey(REG_Voice);
                if (IsRegeditKeyExist(voc, REG_Enable))
                {
                    value = voc.GetValue(REG_Enable).ToString();
                }
                else
                {
                    if (value == Value_Empty)
                        voc.SetValue(REG_Enable, InitEnable);
                    value = InitEnable;
                }
               
                voc.Close();
                config.Close();
                callingsystem.Close();
                software.Close();
                key.Close();
            }
            catch (Exception exp)
            {
                System.Windows.Forms.MessageBox.Show(exp.Message);
            }
        }

        private static bool IsRegeditKeyExist(RegistryKey RegBoot, string RegKeyName)
        {

            string[] subkeyNames;
            subkeyNames = RegBoot.GetValueNames();
            foreach (string keyName in subkeyNames)
            {

                if (keyName == RegKeyName)  //判断键值的名称
                {
                    return true;
                }
            }
            return false;
        }

        private static bool IsRegeditItemExist(RegistryKey RegBoot, string ItemName)
        {
            if (ItemName.IndexOf("\\") <= -1)
            {
                string[] subkeyNames;
                subkeyNames = RegBoot.GetValueNames();
                foreach (string ikeyName in subkeyNames)  //遍历整个数组
                {
                    if (ikeyName == ItemName) //判断子项的名称
                    {
                        return true;
                    }
                }
                return false;
            }
            else
            {
                string[] strkeyNames = ItemName.Split('\\');
                RegistryKey _newsubRegKey = RegBoot.OpenSubKey(strkeyNames[0]);
                string _newRegKeyName = "";
                int i;
                for (i = 1; i < strkeyNames.Length; i++)
                {
                    _newRegKeyName = _newRegKeyName + strkeyNames[i];
                    if (i != strkeyNames.Length - 1)
                    {
                        _newRegKeyName = _newRegKeyName + "\\";
                    }
                }
                return IsRegeditItemExist(_newsubRegKey, _newRegKeyName);
            }
        }
    }
}

CWin32Api.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
namespace CallingSystem.API
{
    public class Win32API
    {

        [StructLayout(LayoutKind.Sequential)]
        public struct tagSCROLLINFO
        {
            public uint cbSize;
            public uint fMask;
            public int nMin;
            public int nMax;
            public uint nPage;
            public int nPos;
            public int nTrackPos;
        }
        public enum fnBar
        {
            SB_HORZ = 0,
            SB_VERT = 1,
            SB_CTL = 2
        }
        public enum fMask
        {
            SIF_ALL,
            SIF_DISABLENOSCROLL = 0X0010,
            SIF_PAGE = 0X0002,
            SIF_POS = 0X0004,
            SIF_RANGE = 0X0001,
            SIF_TRACKPOS = 0X0008
        }
        public struct SCROLLINFO
        {
            /// <summary>
            /// 结构体大小
            /// </summary>
            public uint cbSize;
            /// <summary>
            /// 每个条目所占高度
            /// </summary>
            public uint fMask;
            /// <summary>
            /// 最大条目ID
            /// </summary>
            public int nMin;
            /// <summary>
            /// 最小条目ID
            /// </summary>
            public int nMax;
            /// <summary>
            /// 当前可视化总条目数
            /// </summary>
            public uint nPage;
            /// <summary>
            /// 当前滚动位置
            /// </summary>
            public int nPos;
            public int nTrackPos;
        }
        public enum ScrollInfoMask
        {
            SIF_RANGE = 0x1,
            SIF_PAGE = 0x2,
            SIF_POS = 0x4,
            SIF_DISABLENOSCROLL = 0x8,
            SIF_TRACKPOS = 0x10,
            SIF_ALL = SIF_RANGE + SIF_PAGE + SIF_POS + SIF_TRACKPOS
        }
        public enum ScrollBarDirection
        {
            SB_HORZ = 0,
            SB_VERT = 1,
            SB_CTL = 2,
            SB_BOTH = 3
        }
        public static int MakeLong(short lowPart, short highPart)
        {
            return (int)(((ushort)lowPart) | (uint)(highPart << 16));
        }

        
        public const int SB_THUMBTRACK = 5;
        public const int WM_NULL = 0x0000;
        public const int WM_CREATE = 0x0001;
        public const int WM_DESTROY = 0x0002;
        public const int WM_MOVE = 0x0003;
        public const int WM_SIZE = 0x0005;
        public const int WM_ACTIVATE = 0x0006;
        public const int WM_SETFOCUS = 0x0007 ;
        public const int WM_KILLFOCUS = 0x0008;
        public const int WM_ENABLE = 0x000A;
        public const int WM_SETREDRAW = 0x000B;
        public const int WM_SETTEXT = 0x000C;
        public const int WM_GETTEXT = 0x000D;
        public const int WM_GETTEXTLENGTH = 0x000E;
        public const int WM_PAINT = 0x000F;
        public const int WM_CLOSE = 0x0010;
        public const int WM_QUIT = 0x0012;
        public const int WM_ERASEBKGND = 0x0014;
        public const int WM_SYSCOLORCHANGE = 0x0015;
        public const int WM_SHOWWINDOW = 0x0018;
        public const int WM_WININICHANGE = 0x001A;
        public const int WM_SETCURSOR = 0x0020;
        public const int WM_MOUSEACTIVATE = 0x0021;
        public const int WM_WINDOWPOSCHANGING = 0x0046;
        public const int WM_WINDOWPOSCHANGED = 0x0047;
        public const int WM_NCCREATE = 0x0081;
        public const int WM_NCDESTROY =0x0082  ;
        public const int WM_NCCALCSIZE = 0x0083;
        public const int WM_NCHITTEST = 0x0084;
        public const int WM_NCPAINT = 0x0085;
        public const int WM_SYSCOMMAND = 0x0112;
        public const int WM_HSCROLL = 0x0114;
        public const int WM_VSCROLL = 0x0115;
        public const int WM_CTLCOLOREDIT = 0x0133;
        public const int WM_MOUSEMOVE = 0x0200;
        public const int WM_LBUTTONDOWN = 0x0201;
        public const int WM_LBUTTONUP = 0x0202;
        public const int WM_LBUTTONDBLCLK = 0x0203;
        public const int WM_CAPTURECHANGED = 0x0215;
        public const Int32 IDM_SETTING = 10000;
        //0x0201 WM_LBUTTONDOWN
        //0x0281 WM_IME_SETCONTEXT
        //0x0282 WM_IME_NOTIFY
        //0x0282 WM_IME_NOTIFY
        //0x0202 WM_LBUTTONUP
        //0x0215 WM_CAPTURECHANGED
        //0x0084 WM_NCHITTEST
        //0x0084 WM_NCHITTEST
        //0x0020 WM_SETCURSOR
        //0x0084 WM_SETCURSOR
        //0x0084 WM_NCHITTEST
        //0x0084 WM_NCHITTEST
        //0x0084 WM_NCHITTEST
        //0x0084 WM_NCHITTEST
        //0x0020 WM_SETCURSOR
        //0x0200 WM_SETCURSOR
        //0x000f  WM_PAINT
        //0x0014 WM_ERASEBKGND
        //0x000e WM_GETTEXTLENGTH
        //0x000d WM_GETTEXT
        //0x000e WM_GETTEXTLENGTH
        //0x000d WM_GETTEXT
        //0x0084 WM_NCHITTEST
        //0x0084 WM_NCHITTEST
        //0x0020 WM_SETCURSOR
        //0x0084 WM_NCHITTEST
        //0x0084 WM_NCHITTEST
        //0x0020 WM_SETCURSOR
        //0x0200 WM_MOUSEMOVE
        //0x0084 WM_NCHITTEST
        //0x0084 WM_NCHITTEST
        //0x0020 WM_SETCURSOR
        //0x0200 WM_MOUSEMOVE
        //0x0084  WM_NCHITTEST
        //0x0084 WM_NCHITTEST
        //0x0020  WM_SETCURSOR
        //0x0200 WM_MOUSEMOVE
        //0x0084 WM_NCHITTEST
        //0x0084 WM_NCHITTEST
        //0x0020 WM_SETCURSOR
        //0x0200 WM_MOUSEMOVE
        //0x02a3 WM_MOUSELEAVE
        //0x000f WM_PAINT
        //0x0014 WM_ERASEBKGND
        //0x000e WM_GETTEXTLENGTH
        //0x000d WM_GETTEXT
        //0x000e WM_GETTEXTLENGTH
        //0x000d WM_GETTEXT

        public const int WM_IME_SETCONTEXT = 0x0281;
        public const int WM_IME_NOTIFY = 0x0282;
        public const int WM_IME_CONTROL = 0x0283;
        public const int WM_IME_COMPOSITIONFULL = 0x0284;
        public const int WM_IME_SELECT = 0x0285;
        public const int WM_IME_CHAR = 0x0286;
        public const int WM_IME_REQUEST = 0x0288;

        public const int WM_MOUSEHOVER = 0x02A1;
        public const int WM_MOUSELEAVE = 0x02A3;
        public const int WM_HOTKEY = 0x0312;
            
        public const int MF_STRING = 0x0000;
        public const int MF_SEPARATOR = 0x0800;
        public const int SC_MOVE = 0xF010;
        public const int HTCAPTION = 0x0002;

        public const uint SC_CLOSE = 0xF060;//关闭
        public const uint SC_MINIMIZE = 0xF020;
        public const uint SC_MAXIMIZE = 0xF030;
        public const uint MF_BYCOMMAND = 0x0000; //按命令方式
        public const uint MF_GRAYED = 0x0001;    //灰掉
        public const uint MF_DISABLED = 0x0002;  //不可用
        public const uint MA_ACTIVATE = 0x0001;  //不可用
        public const uint MA_ACTIVATEANDEAT = 0x0002;  //不可用
        public const uint MA_NOACTIVATE = 0x0003;  //不可用
        public const uint MA_NOACTIVATEANDEAT = 0x0004;  //不可用

        public const int UWM_ActiveGlobalSetting = 2000;
        public const int UWM_ActiveMain = 2001;
        public const int UWM_enter = 2001;

        public const int UHKWP_DMEDICINE = 1000;
        public const int UHKWP_DVOICE = 1001;
        public const int UHKWP_DOUTPUTINFO = 1002;
        public const int UHKWP_ABOUT = 1003;
        public const int UHKWP_PRINTDebug = 1004;
        public const int UHKWP_PLCCUT = 1005;
        public const int UHKWP_Exit = 1006;
        public const int UHKWP_OpenPrintURL = 1007;
        public const int UHKWP_OpenCompanyURL = 1008;
        public const int UHKWP_SHOWHIDE = 1009;
        public const int UHKWP_DModifyMedicineBoxLoction = 1010;
        public const int UHKWP_OnMedicineInMachine = 1011;
        public const int UHKWP_OnFindMedicineInMachine = 1012;
        public const int UHKWP_OnShowHPMTray = 1013;
        public const int UHKWP_OnUserManager = 1014;
        public const int UHKWP_OnFormPreviewMBCurrentQuantity = 1015;
        public const int UHKWP_ReadDominoStatusError = 1016;

        public const int UHKWP_FormCreatePrescription = 1017;
        public const int UHKWP_FormOutPut = 1018;
        public const int UHKWP_CDistributeMedicineMessageBox = 1019;
        public const int UHKWP_CDMMB = 1020;
        public const int UHKWP_GlobalSettings = 1021;
        public const int UHKWP_HotKey = 1022;
        public const int UHKWP_FormVoiceCommand = 1023;
        public const int UHKWP_DetectSetting = 1024;
        public const int UHKWP_FormPreviewMedicineExpirationDate = 1025;
        public const int UHKWP_JiaoHao = 1026;

        
        //下面是可用的常量,根据不同的动画效果声明自己需要的
        private const int AW_HOR_POSITIVE = 0x0001;//自左向右显示窗口,该标志可以在滚动动画和滑动动画中使用。使用AW_CENTER标志时忽略该标志
        private const int AW_HOR_NEGATIVE = 0x0002;//自右向左显示窗口,该标志可以在滚动动画和滑动动画中使用。使用AW_CENTER标志时忽略该标志
        private const int AW_VER_POSITIVE = 0x0004;//自顶向下显示窗口,该标志可以在滚动动画和滑动动画中使用。使用AW_CENTER标志时忽略该标志
        private const int AW_VER_NEGATIVE = 0x0008;//自下向上显示窗口,该标志可以在滚动动画和滑动动画中使用。使用AW_CENTER标志时忽略该标志该标志
        private const int AW_CENTER = 0x0010;//若使用了AW_HIDE标志,则使窗口向内重叠;否则向外扩展
        private const int AW_HIDE = 0x10000;//隐藏窗口
        private const int AW_ACTIVE = 0x20000;//激活窗口,在使用了AW_HIDE标志后不要使用这个标志
        private const int AW_SLIDE = 0x40000;//使用滑动类型动画效果,默认为滚动动画类型,当使用AW_CENTER标志时,这个标志就被忽略
        private const int AW_BLEND = 0x80000;//使用淡入淡出效果

        [DllImport("user32.dll")]
        public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);

        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        public static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);
        /// <summary>
        /// 不激活
        /// </summary>
       public const int WS_EX_NOACTIVATE = 0x08000000;
        [DllImport("user32")]
        private static extern bool AnimateWindow(IntPtr hwnd, int dwTime, int dwFlags);
        [DllImport("user32.dll", EntryPoint = "GetScrollInfo")]
        public static extern bool GetScrollInfo(IntPtr hwnd, int fnBar, ref SCROLLINFO lpsi);
        [DllImport("user32.dll", EntryPoint = "SetScrollInfo")]
        public static extern int SetScrollInfo(IntPtr hwnd, int fnBar, [In] ref SCROLLINFO lpsi, bool fRedraw);

        [DllImport("user32.dll")]
        public static extern IntPtr GetActiveWindow();//获得当前活动窗体
        [DllImport("user32.dll")]
        public static extern IntPtr SetActiveWindow(IntPtr hwnd);//设置活动窗体

        [DllImport("user32.dll")]
        public static extern IntPtr GetFocus();
       
        public enum eSliderType
        {
            /// <summary>
            /// 左上→
            /// </summary>
            TopLR = 0,
            /// <summary>
            /// 右上←
            /// </summary>
            TopRL,
            /// <summary>
            /// 中→
            /// </summary>
            MiddleLR,
            /// <summary>
            /// 中←
            /// </summary>
            MiddleRL,
            /// <summary>
            /// 下→
            /// </summary>
            BottomLR,
            /// <summary>
            /// 下←
            /// </summary>
            BottomRL,
            /// <summary>
            /// 左↓
            /// </summary>
            LeftTB,
            /// <summary>
            /// 左↑
            /// </summary>
            LeftBT,
            /// <summary>
            /// 右↓
            /// </summary>
            RightTB,
            /// <summary>
            /// 右↑
            /// </summary>
            RightBT,
            /// <summary>
            /// 中↓
            /// </summary>
            CenterTB,
            /// <summary>
            /// 中↑
            /// </summary>
            CenterBT,
            /// <summary>
            /// 淡入淡出
            /// </summary>
            MiddleCenterBlend,
            /// <summary>
            /// 扩散收缩
            /// </summary>
            MiddleCenterAdd,
        }
        public static eSliderType AnimateSliderType = eSliderType.CenterTB;

        public static void FormClosing(Form hwnd)
        {
            try
            {
                int awStyle = 0;
                if (
                    AnimateSliderType == eSliderType.RightBT
                 || AnimateSliderType == eSliderType.LeftBT
                 || AnimateSliderType == eSliderType.CenterBT
                    )
                {
                    awStyle = AW_VER_POSITIVE;
                }
                else if (
                   AnimateSliderType == eSliderType.RightTB
                || AnimateSliderType == eSliderType.LeftTB
                || AnimateSliderType == eSliderType.CenterTB
                   )
                {
                    awStyle = AW_VER_NEGATIVE ;

                }
                else if (
                   AnimateSliderType == eSliderType.BottomLR
                || AnimateSliderType == eSliderType.TopLR
                || AnimateSliderType == eSliderType.MiddleLR
                   )
                {
                    awStyle =AW_HOR_NEGATIVE ;
                }
                else if (
                   AnimateSliderType == eSliderType.BottomRL
                || AnimateSliderType == eSliderType.TopRL
                || AnimateSliderType == eSliderType.MiddleRL
                   )
                {
                    awStyle = AW_HOR_POSITIVE;

                }

                if (AnimateSliderType == eSliderType.MiddleCenterAdd)
                {
                    if (hwnd != null && hwnd.IsDisposed == false)
                        AnimateWindow(hwnd.Handle, 1000,  AW_CENTER | AW_HIDE);
                }
                else if (AnimateSliderType == eSliderType.MiddleCenterBlend)
                {
                    if (hwnd != null && hwnd.IsDisposed == false)
                        AnimateWindow(hwnd.Handle, 1000, AW_BLEND | AW_HIDE);
                }
                else
                {
                    if (hwnd != null && hwnd.IsDisposed == false)
                        AnimateWindow(hwnd.Handle, 1000, awStyle | AW_SLIDE | AW_HIDE);
                }

            }
            catch(Exception e)
            {
            }
        }
        public static void FormLoad(Form hwnd)
        {
            if (hwnd != null && hwnd.IsDisposed == false)
            {
                int x = 0;
                int y = 0;
                //int x = Screen.PrimaryScreen.WorkingArea.Right - hwnd.Width;
                //int y = Screen.PrimaryScreen.WorkingArea.Bottom - hwnd.Height;
                if(AnimateSliderType == eSliderType.CenterTB)
                {
                    x = Screen.PrimaryScreen.WorkingArea.Width / 2 - hwnd.Width / 2;
                    y = Screen.PrimaryScreen.WorkingArea.Top;
                }
                else if (AnimateSliderType == eSliderType.CenterBT
                    )
                {
                    x = Screen.PrimaryScreen.WorkingArea.Width / 2 - hwnd.Width / 2;
                    y = Screen.PrimaryScreen.WorkingArea.Bottom - hwnd.Height;
                }
                else if (AnimateSliderType == eSliderType.MiddleLR)
                {
                    x = Screen.PrimaryScreen.WorkingArea.Left;
                    y = Screen.PrimaryScreen.WorkingArea.Height / 2 - hwnd.Height / 2;
                }
                else if (AnimateSliderType == eSliderType.MiddleRL
                    )
                {
                    x = Screen.PrimaryScreen.WorkingArea.Right - hwnd.Width;
                    y = Screen.PrimaryScreen.WorkingArea.Height / 2 - hwnd.Height / 2;
                }
                else if (AnimateSliderType == eSliderType.LeftTB
                    || AnimateSliderType == eSliderType.TopLR
                    )
                {
                    x = 0;
                    y = Screen.PrimaryScreen.WorkingArea.Top;
                }
   
                else if (
                    AnimateSliderType == eSliderType.LeftBT
                ||    AnimateSliderType == eSliderType.BottomLR
                    )
                {
                    x = 0;
                    y = Screen.PrimaryScreen.WorkingArea.Bottom - hwnd.Height;
                }
                else if (AnimateSliderType == eSliderType.RightTB
                    || AnimateSliderType == eSliderType.TopRL
                    )
                {
                    x = Screen.PrimaryScreen.WorkingArea.Right - hwnd.Width;
                    y = Screen.PrimaryScreen.WorkingArea.Top;
                }

                else if (AnimateSliderType == eSliderType.RightBT 
                    ||   AnimateSliderType == eSliderType.BottomRL 
                    )
                {
                    x = Screen.PrimaryScreen.WorkingArea.Right - hwnd.Width;
                    y = Screen.PrimaryScreen.WorkingArea.Bottom - hwnd.Height;
                }
                else if (AnimateSliderType == eSliderType.MiddleCenterBlend
                    || AnimateSliderType == eSliderType.MiddleCenterAdd
                    )
                {
                    x = Screen.PrimaryScreen.WorkingArea.Width / 2 - hwnd.Width / 2;
                    y = Screen.PrimaryScreen.WorkingArea.Height / 2 - hwnd.Height / 2;
                }


                int awStyle = 0;
                if (
                    AnimateSliderType == eSliderType.RightBT
                 || AnimateSliderType == eSliderType.LeftBT
                 || AnimateSliderType == eSliderType.CenterBT
                    )
                {
                   awStyle = AW_VER_NEGATIVE;
                }
                else if (
                   AnimateSliderType == eSliderType.RightTB
                || AnimateSliderType == eSliderType.LeftTB
                || AnimateSliderType == eSliderType.CenterTB
                   )
                {
                   awStyle = AW_VER_POSITIVE;

                }
                else if (
                   AnimateSliderType == eSliderType.BottomLR
                || AnimateSliderType == eSliderType.TopLR
                || AnimateSliderType == eSliderType.MiddleLR
                   )
                {
                   awStyle = AW_HOR_POSITIVE;
                }
                else if (
                   AnimateSliderType == eSliderType.BottomRL
                || AnimateSliderType == eSliderType.TopRL
                || AnimateSliderType == eSliderType.MiddleRL
                   )
                {
                   awStyle = AW_HOR_NEGATIVE;
                }

                hwnd.Location = new Point(x, y);//设置窗体在屏幕右下角显示

                if (AnimateSliderType == eSliderType.MiddleCenterAdd)
                {

                    AnimateWindow(hwnd.Handle, 1000, AW_CENTER | AW_ACTIVE);
                }
                else if (AnimateSliderType == eSliderType.MiddleCenterBlend)
                {

                    AnimateWindow(hwnd.Handle, 1000, AW_BLEND );
                }
                else
                {
                     AnimateWindow(hwnd.Handle, 1000, AW_SLIDE | AW_ACTIVE | awStyle);
                }
            }

        }

        //[DllImport("User32.dll", CharSet = CharSet.Auto, EntryPoint = "SendMessage")]
        //static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

        [DllImport("user32.dll", EntryPoint = "ShowScrollBar")]
        public static extern int ShowScrollBar(IntPtr hWnd, int bar, int show);


        //[DllImport("user32.dll")]
        //private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);
       // [DllImport("user32.dll")]
       // private static extern bool AppendMenu(IntPtr hMenu, Int32 wFlags, Int32 wIDNewItem, string lpNewItem);

        #region 系统菜单处理
        /// <summary>
        /// 获取系统菜单
        /// </summary>
        /// <param name="hWnd"></param>
        /// <param name="bRevert"> </param>
        /// <returns></returns>
        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);

        /// <summary>
        /// 添加系统子菜单
        /// </summary>
        /// <param name="hMenu">父级菜单</param>
        /// <param name="uFlags">子菜单类型:MF_STRING MF_SEPARATOR</param>
        /// <param name="uIDNewItem">子菜单编号(MF_SEPARATOR - 0)</param>
        /// <param name="lpNewItem">子菜单名称(MF_SEPARATOR - string.Empty)</param>
        /// <returns></returns>
        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern bool AppendMenu(IntPtr hMenu, int uFlags, int uIDNewItem, string lpNewItem);
        /// <summary>
        /// 插入系统子查单
        /// </summary>
        /// <param name="hMenu">父级菜单</param>
        /// <param name="uPosition">子菜单插入位置</param>
        /// <param name="uFlags">子菜单类型:MF_STRING MF_SEPARATOR</param>
        /// <param name="uIDNewItem">子菜单编号(MF_SEPARATOR - 0)</param>
        /// <param name="lpNewItem">子菜单名称(MF_SEPARATOR - string.Empty)</param>
        /// <returns></returns>

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern bool InsertMenu(IntPtr hMenu, int uPosition, int uFlags, int uIDNewItem, string lpNewItem);

        public const int  ID_SYSMENU_ABOUT = 0x0001;

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern bool DeleteMenu(IntPtr hMenu, uint uPosition, uint uFlags);


        [DllImport("user32.dll", EntryPoint = "GetWindowLong", CharSet = CharSet.Auto)]
        public static extern int GetWindowLong(HandleRef hWnd, int nIndex);
        [DllImport("user32.dll", EntryPoint = "SetWindowLong", CharSet = CharSet.Auto)]
        public static extern IntPtr SetWindowLong(HandleRef hWnd, int nIndex, int dwNewLong);

        public const int WS_SYSMENU = 0x00080000;

        public const int WS_MINIMIZEBOX = 0x20000; // 最大最小化按钮
        public static void ShowSYSMENU(Form form)
        {
            int windowLong = (GetWindowLong(new HandleRef(form, form.Handle), -16));
          //  SetWindowLong(new HandleRef(form, form.Handle), -16, windowLong | WS_SYSMENU | 0x20000 | 0x40000);
            SetWindowLong(new HandleRef(form, form.Handle), -16, windowLong | WS_SYSMENU | WS_MINIMIZEBOX);
            IntPtr menu = GetSystemMenu(form.Handle, false);




            if (!form.ControlBox)
            {
                DeleteMenu(menu, SC_CLOSE, 0x0);//关闭  
                DeleteMenu(menu, SC_MINIMIZE, 0x0);//最小化  
                DeleteMenu(menu, SC_MAXIMIZE, 0x0);//最大化  
            }
            else
            {
                if (!form.MinimizeBox)
                {
                    DeleteMenu(menu, SC_MINIMIZE, 0x0);//最小化  
                }
                if (!form.MaximizeBox)
                {
                    DeleteMenu(menu, SC_MAXIMIZE, 0x0);//最大化  
                }
            }

        } 
        #endregion

        #region
        /// <summary>
        /// 如果函数执行成功,返回值不为0。
        /// 如果函数执行失败,返回值为0。要得到扩展错误信息,调用GetLastError。
        /// </summary>
        /// <param name="hWnd"></param>
        /// <param name="id"></param>
        /// <param name="fsModifiers"></param>
        /// <param name="vk"></param>
        /// <returns></returns>
        [DllImport("user32.dll", SetLastError = true)]
        public static extern bool RegisterHotKey(
            IntPtr hWnd,                //要定义热键的窗口的句柄
            int id,                     //定义热键ID(不能与其它ID重复)
            KeyModifiers fsModifiers,   //标识热键是否在按Alt、Ctrl、Shift、Windows等键时才会生效
            Keys vk                     //定义热键的内容
            );
        /// <summary>
        /// 
        /// </summary>
        /// <param name="hWnd"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        [DllImport("user32.dll", SetLastError = true)]
        public static extern bool UnregisterHotKey(
            IntPtr hWnd,                //要取消热键的窗口的句柄
            int id                      //要取消热键的ID
            );
        /// <summary>
        /// 定义了辅助键的名称(将数字转变为字符以便于记忆,也可去除此枚举而直接使用数值)
        /// </summary>
        [Flags()]
        public enum KeyModifiers
        {
            None = 0,
            Alt = 1,
            Ctrl = 2,
            Shift = 4,
            WindowsKey = 8
        }
        #endregion
        #region 声明 API 函数
        /// <summary>
        /// 该函数将指定的消息发送到一个或多个窗口。
        /// </summary>
        /// <param name="hWnd">其窗口程序将接收消息的窗口的句柄。</param>
        /// <param name="msg">指定被发送的消息</param>
        /// <param name="wParam">指定附加的消息指定信息</param>
        /// <param name="lParam">指定附加的消息指定信息</param>
        /// <returns>返回值指定消息处理的结果,依赖于所发送的消息。</returns>
        [DllImport("User32.dll", EntryPoint = "SendMessage")]
        public static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);

        public static IntPtr SendMessage(IntPtr hWnd, int msg, int wParam, int lParam)
        {
            return SendMessage(hWnd, msg, (IntPtr)wParam, (IntPtr)lParam);
        }
        /// <summary>
        /// 该函数将一个消息放入(寄送)到与指定窗口创建的线程相联系消息队列里,不等待线程处理消息就返回,是异步消息模式。消息队列里的消息通过调用GetMessage和PeekMessage取得。
        /// </summary>
        /// <param name="hWnd">其窗口程序接收消息的窗口的句柄。</param>
        /// <param name="msg">指定被寄送的消息。</param>
        /// <param name="wParam">指定附加的消息特定的信息。</param>
        /// <param name="lParam">指定附加的消息特定的信息。</param>
        /// <returns>如果函数调用成功,返回非零,否则函数调用返回值为零</returns>
        [DllImport("User32.dll", EntryPoint = "PostMessage")]
        public static extern IntPtr PostMessage(int hWnd, int msg, IntPtr wParam, IntPtr lParam);

        public static IntPtr PostMessage(IntPtr hWnd, int msg, int wParam, int lParam)
        {
            return PostMessage((int)hWnd, msg, (IntPtr)wParam, (IntPtr)lParam);
        }
        /// <summary>
        /// 检索处理顶级窗口的类名和窗口名称匹配指定的字符串。
        /// </summary>
        /// <param name="lpClassName">类名</param>
        /// <param name="lpWindowName">窗口名</param>
        /// <returns></returns>
        [DllImport("User32.dll", EntryPoint = "FindWindow")]
        public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll")]
        public static extern bool ReleaseCapture();




        #endregion

        #region 外部程序
        public static void Start(string appName, string Title)
        {
            try
            {
                Process p = Process.Start(AppDomain.CurrentDomain.BaseDirectory + @"SoundAcquisition.exe");
            }
            catch (ArgumentException ex)
            {
                MessageBox.Show(ex.Message, Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        /// <summary>
        /// 启动外部程序,等待其退出
        /// </summary>
        /// <param name="appName"></param>
        public static void StartWaitExitBySleep(string appName, string Title)
        {
            try
            {
                Process proc = Process.Start(appName);
                if (proc != null)
                {
                    proc.WaitForExit(3000);
                    if (proc.HasExited) MessageBox.Show(String.Format("外部程序 {0} 已经退出!", appName), Title,
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                    else
                    {
                        // 如果外部程序没有结束运行则强行终止之。
                        proc.Kill();
                        MessageBox.Show(String.Format("外部程序 {0} 被强行终止!", appName), Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    }
                }
            }
            catch (ArgumentException ex)
            {
                MessageBox.Show(ex.Message, Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        /// <summary>
        /// 启动外部程序,无限等待其退出
        /// </summary>
        /// <param name="appName"></param>
        public static void StartWaitExit(string appName, string Title)
        {
            try
            {
                Process proc = Process.Start(appName);
                if (proc != null)
                {
                    proc.WaitForExit();
                    MessageBox.Show(String.Format("外部程序 {0} 已经退出!", appName), Title,
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (ArgumentException ex)
            {
                MessageBox.Show(ex.Message, Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public static string APPNAME = "";
        public static string TITLE = "";
        /// <summary>
        /// 启动外部程序,通过事件监视其退出
        /// </summary>
        /// <param name="appName"></param>
        public static void StartWaitExitByEvent(string appName, string Title)
        {
            try
            {
                APPNAME = appName;
                TITLE = Title;
                //启动外部程序
                Process proc = Process.Start(appName);
                if (proc != null)
                {
                    //监视进程退出
                    proc.EnableRaisingEvents = true;
                    //指定退出事件方法
                    proc.Exited += new EventHandler(proc_Exited);
                }
            }
            catch (ArgumentException ex)
            {
                MessageBox.Show(ex.Message, Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private static void proc_Exited(object sender, EventArgs e)
        {
            MessageBox.Show(String.Format("外部程序 {0} 已经退出!", APPNAME), TITLE,
            MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        public static bool IsInternetAvailable()
        {
            try
            {
                Dns.GetHostEntry("www.iflytek.com"); //using System.Net;
                return true;
            }
            catch (SocketException ex)
            {
                return false;
            }
            catch (Exception exp)
            {
                return false;
            }
            finally
            {
               // return false;
            }
        }
        public static void StartWithParam(string appName, string Title)
        {
            try
            {
                ProcessStartInfo psi = new ProcessStartInfo();
                psi.FileName = appName;
                psi.UseShellExecute = false;
                psi.CreateNoWindow = true;
                Process.Start(psi);
            }
            catch (Exception exp)
            {
                MessageBox.Show(exp.Message, Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public static void CloseByProcessName(string ProcessName, string Title)
        {
            try
            {
                Process[] ps = Process.GetProcesses();//获取计算机上所有进程 
                foreach (Process p in ps)
                {
                    try
                    {
                        if (p.ProcessName == ProcessName && Process.GetCurrentProcess().Id != p.Id)//判断进程名称 
                        {
                            p.Kill();//停止进程 
                        }
                    }
                    catch (Exception exp)
                    {

                    }
                }
            }
            catch (Exception exp)
            {
                MessageBox.Show(exp.Message, Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion

    }


    
        #region 解决闪烁的问题
        //protected void InitUI()
        //{
        //    //开启双缓冲
        //    this.SetStyle(ControlStyles.DoubleBuffer, true);
        //    this.SetStyle(ControlStyles.UserPaint, true);
        //    this.SetStyle(ControlStyles.ResizeRedraw, true);
        //    this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
        //    this.SetStyle(ControlStyles.AllPaintingInWmPaint, true); // 禁止擦除背景.
        //}
        //protected override CreateParams CreateParams
        //{
        //    get
        //    {
        //        CreateParams paras = base.CreateParams;
        //        paras.ExStyle |= 0x02000000;
        //        return paras;
        //    }
        //}
        #endregion
     

    public class SubWindow : NativeWindow
    {
        private int m_Horz = 0;
        private int m_Show = 0;

        public SubWindow(int p_Horz, int p_Show)
        {
            m_Horz = p_Horz;
            m_Show = p_Show;
        }

        public static void SetScrollBar(IntPtr p_ControlHandle, int p_Horz, int p_Show)
        {
            SubWindow _SubWindow = new SubWindow(p_Horz, p_Show);
            _SubWindow.AssignHandle(p_ControlHandle);
        }

        
    }  
    
}

CUserAPI.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace CallingSystem.API
{
    public  class CUserAPI
    {
        public const int UWM_SoundAcquisitionStart = 0x0400;
        public const int UWM_SoundAcquisitionStop = 0x0401;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值