2012年05月15日 10:45 请注意,使用下面程序时,必须提供class name和窗口名. namespace PJBoo import System import System.Runtime.InteropServices class FindWindow: [DllImport("user32")] static def EnumChildWindows(window as IntPtr,callback as EnumWindowsProc,i as IntPtr) as bool: pass callable EnumWindowsProc(hWnd as IntPtr,parameter as IntPtr) as bool [DllImport("user32",EntryPoint:"FindWindowEx")] static def FindWindowEx(hwndParent as IntPtr,hwndChildAfter as IntPtr,lpszClass as string,lpszWindow as string) as IntPtr: pass _classname as string _caption as string _hwnd as IntPtr public def constructor(hwndParent as IntPtr,classname as string,caption as string): _hwnd=IntPtr.Zero _classname=classname _caption=caption FindChildClassHwnd(hwndParent,IntPtr.Zero) public def FoundHandle() as IntPtr: return _hwnd private def FindChildClassHwnd(hwndParent as IntPtr,lParam as IntPtr) as bool: childProc=EnumWindowsProc(FindChildClassHwnd) hwnd=FindWindowEx(hwndParent,IntPtr.Zero,_classname,_caption) if hwnd!=IntPtr.Zero: _hwnd=hwnd return false EnumChildWindows(hwndParent,childProc,IntPtr.Zero) return true |
2012年05月15日 10:29 namespace PJBoo //static void Main() //{ // SingleApp.Run(new FrmMain()); //} //static void Main() //{ // if(SingleApp.Run()==false) // { // return; // } //} import System import System.Runtime.InteropServices import System.Diagnostics import System.Threading import System.Reflection import System.IO import System.Windows.Forms class SingleApp: static _mutex as Mutex [DllImport("user32.dll")] static def ShowWindow(hwnd as IntPtr,nCmdShow as int) as int: pass static def SetForegroundWindow(hwnd as IntPtr) as int: pass static def IsIconic(hwnd as IntPtr) as int: pass public def constructor(): pass private static def GetCurrentInstanceWindowHandle() as IntPtr: hwnd=IntPtr.Zero process=Process.GetCurrentProcess() processes=Process.GetProcessesByName(process.ProcessName) for _process as Process in processes: if _process.Id != process.Id and _process.MainModule.FileName == process.MainModule.FileName and _process.MainWindowHandle!=IntPtr.Zero: hwnd=_process.MainWindowHandle break return hwnd private static def SwitchToCurrentInstance(): hwnd=GetCurrentInstanceWindowHandle() if hwnd!=IntPtr.Zero: if IsIconic(hwnd)!=0: ShowWindow(hwnd,9) SetForegroundWindow(hwnd) public static def Run(frmMain as System.Windows.Forms.Form) as bool: if IsAlreadyRunning(): SwitchToCurrentInstance() return false Application.Run(frmMain) return true public static def Run() as bool: if IsAlreadyRunning(): return false return true private static def IsAlreadyRunning() as bool: strLoc=Assembly.GetExecutingAssembly().Location fileInfo=FileInfo(strLoc) sExeName=fileInfo.Name bCreatedNew=false _mutex=Mutex(true,"Global\\"+sExeName,bCreatedNew) if bCreatedNew: _mutex.ReleaseMutex() return not bCreatedNew 至于实现什么功能,我想不用我多说吧. |
2012年05月15日 10:22 最近,使用Sharpdevelop来做一些C#的学习,发现其中还有个Boo语言,感觉是对C#语言的扩充,使其程序更加简洁,就学了一点. 于是,就将之前的C#的IniFile类,转换成了Boo的C#,如下: namespace PJBoo import System import System.Runtime.InteropServices import System.Text //ini=IniFile("C:\\test.ini") //ini.Write("Info","Name",name.Text) //ini.Write("Info","Last Name",lname.Text) //ini=IniFile("C:\\test.ini") //name.Text=ini.Read("Info","Name") //lname.Text=ini.Read("Info","Last Name") class IniFile: _path as string [DllImport("kernel32",SetLastError:true)] static def WritePrivateProfileString(section as string,key as string,val as string,filePath as string) as long: pass [DllImport("kernel32")] static def GetPrivateProfileString(section as string,key as string,defi as string,retVal as StringBuilder,size as int,filePath as string) as int: pass public def constructor(path as string): _path=path public def Write(section as string,key as string,value as string): WritePrivateProfileString(section,key,value,_path) public def Read(section as string,key as string) as string: temp=StringBuilder(255) GetPrivateProfileString(section,key,"",temp,255,_path) return temp.ToString() 该语言主要采用缩进作为区别,因此,没有了C#中的{}. 语法有点类似与python和vb. |
2012年05月10日 9:45 闲来无事,写了一个用ListView实现编辑二进制文件的程序,并且支持多标签浏览,也算是练习TabControl了. 

 输入时需要用到数字键盘的键,完成之后按Enter键. 注意,输入的数据的大小只能在0-255之间. 主要源程序:
/* * Created by SharpDevelop. * User: PengJun * Date: 2012-5-9 * Time: 12:47 * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; using System.IO; using System.Diagnostics; namespace BinaryEditor { /// <summary> /// Description of MainForm. /// </summary> public partial class MainForm : Form { private ListViewItem.ListViewSubItem lvsi=null; private TextBox editTextBox=null; public MainForm() { // // The InitializeComponent() call is required for Windows Forms designer support. // InitializeComponent(); // // TODO: Add constructor code after the InitializeComponent() call. // toolStripStatusLabel1.Text=""; toolStripStatusLabel2.Text=""; } void OpenToolStripMenuItemClick(object sender, EventArgs e) { OpenFileDialog ofd=new OpenFileDialog(); ofd.Multiselect=true; if(ofd.ShowDialog()==DialogResult.OK) { for(int i=0;i<ofd.FileNames.Length;i++) { LoadFile(ofd.FileNames[i]); } } } void LoadFile(string filePath) { TabPage tp=new TabPage(); ListView lv=new ListView(); tp.Text=Path.GetFileName(filePath); lv.Anchor=AnchorStyles.Top|AnchorStyles.Bottom|AnchorStyles.Left|AnchorStyles.Right; lv.Location=new Point(0,0); lv.Size=new Size(tp.Width,tp.Height); lv.GridLines=true; lv.View=View.Details; lv.Name=Path.GetFileNameWithoutExtension(filePath); lv.MouseUp+=new MouseEventHandler(lv_MouseUp); lv.FullRowSelect=true; lv.MultiSelect=false; tp.Controls.Add(lv); tabControl1.TabPages.Add(tp); tabControl1.SelectedTab=tp; Stopwatch sw=new Stopwatch(); sw.Start(); using(BinaryReader br=new BinaryReader(File.Open(filePath,FileMode.Open))) { long length=br.BaseStream.Length; int col=0; int row=0; int no=0; int rows=(int)Math.Ceiling(length/256.0); ListViewItem lvi; ListViewItem.ListViewSubItem lvsi=new ListViewItem.ListViewSubItem(); for(int i=0;i<256;i++) { lv.Columns.Add(i.ToString(),40,HorizontalAlignment.Center); } for(int i=0;i<rows;i++) { lvi=new ListViewItem(); lvi.Text=i.ToString(); lv.Items.Add(lvi); } lv.BeginUpdate(); while(no<length) { no++; byte b=br.ReadByte(); lvsi.Text=b.ToString(); lv.Items[row].SubItems.Add(lvsi); lvsi=new ListViewItem.ListViewSubItem(); col++; if(col==256) { row++; col=0; } } lv.EndUpdate(); } sw.Stop(); toolStripStatusLabel1.Text=sw.ElapsedMilliseconds.ToString()+"ms"; } void lv_MouseUp(object sender, MouseEventArgs e) { TabPage currentTabPage=tabControl1.SelectedTab; string listViewName=currentTabPage.Text.Substring(0,currentTabPage.Text.Length-4); ListView currentListView=(ListView)currentTabPage.Controls.Find(listViewName,false)[0]; //delete the old text box if(this.editTextBox!=null) { currentListView.Controls.Remove(this.editTextBox); this.editTextBox=null; } ListViewItem lvi=currentListView.GetItemAt(e.X,e.Y); ListViewItem.ListViewSubItem lvsi=lvi.GetSubItemAt(e.X,e.Y); int nColIndex=lvi.SubItems.IndexOf(lvsi); int nRowIndex=currentListView.SelectedIndices[0]; toolStripStatusLabel2.Text="("+nRowIndex.ToString()+","+nColIndex.ToString()+")"; TextBox editTextBox=new TextBox(); editTextBox.Text=lvsi.Text; editTextBox.Location=new Point(lvsi.Bounds.Left,lvsi.Bounds.Top); editTextBox.Size=new Size(lvsi.Bounds.Width,lvsi.Bounds.Height); editTextBox.Visible=true; editTextBox.KeyUp+=new KeyEventHandler(editTextBox_KeyUp); currentListView.Controls.Add(editTextBox); this.lvsi=lvsi; this.editTextBox=editTextBox; editTextBox.Focus(); editTextBox.Select(0,editTextBox.Text.Length); } void editTextBox_KeyUp(object sender, KeyEventArgs e) { if(e.KeyCode==Keys.Enter) { TabPage currentTabPage=tabControl1.SelectedTab; string listViewName=currentTabPage.Text.Substring(0,currentTabPage.Text.Length-4); ListView currentListView=(ListView)currentTabPage.Controls.Find(listViewName,false)[0]; try { byte b=byte.Parse(this.editTextBox.Text); this.lvsi.Text=b.ToString(); currentListView.Controls.Remove(this.editTextBox); this.editTextBox=null; } catch(Exception ex) { currentListView.Controls.Remove(this.editTextBox); this.editTextBox=null; MessageBox.Show(ex.Message,"Exception"); } return; } if(!(e.KeyCode>= Keys.NumPad0 && e.KeyCode<=Keys.NumPad9)) { MessageBox.Show("Must use the numeric pad 0~9.","Info"); } } void CloseCurrentTabToolStripMenuItemClick(object sender, EventArgs e) { int selectIndex=tabControl1.SelectedIndex; tabControl1.TabPages.Remove(tabControl1.SelectedTab); tabControl1.SelectedIndex=selectIndex-1; GC.Collect(); } void ExitToolStripMenuItemClick(object sender, EventArgs e) { Close(); } void SaveToolStripMenuItemClick(object sender, EventArgs e) { SaveFileDialog sfd=new SaveFileDialog(); if(sfd.ShowDialog()==DialogResult.OK) { using(BinaryWriter bw=new BinaryWriter(File.OpenWrite(sfd.FileName))) { TabPage currentTabPage=tabControl1.SelectedTab; string listViewName=currentTabPage.Text.Substring(0,currentTabPage.Text.Length-4); ListView currentListView=(ListView)currentTabPage.Controls.Find(listViewName,false)[0]; for(int i=0;i<currentListView.Items.Count;i++) { for(int j=1;j<currentListView.Items[i].SubItems.Count;j++) { string text=currentListView.Items[i].SubItems[j].Text; byte b=Convert.ToByte(text); bw.Write(b); } } } MessageBox.Show("Save Completely!","Info."); } } } }
|
2012年05月09日 11:56 在C#中,计算程序段的运行时间比较简单,步骤如下: 1 using System.Diagnostics; 2 Stopwatch sw=new Stopwatch(); 3 sw.start() 4 程序段 5 sw.stop(); 6 运行时间可以用毫秒或多少个cpu时钟. 分别为sw.ElapsedMilliseconds和sw.ElapsedTicks. 具体如下: /* * Created by SharpDevelop. * User: pengjun * Date: 2012-5-9 * Time: 11:14 * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ using System; using System.Diagnostics; namespace BinReader { class Program { public static void Main(string[] args) { Stopwatch sw=new Stopwatch(); int nSize=16*16; double[] pNew=null; double[] pOld=null; pNew=new double[nSize]; sw.Start(); for(int i=0;i<10000;i++) { if(pNew!=null) { pNew=null; } pNew=new double[nSize]; pNew.Initialize(); } sw.Stop(); Console.WriteLine("first delete then new : {0} ticks",sw.ElapsedTicks.ToString()); sw.Start(); for(int i=0;i<10000;i++) { if(pOld==null) { pOld=new double[nSize]; pOld.Initialize(); } pOld=null; } sw.Stop(); Console.WriteLine("first check then new : {0} ticks",sw.ElapsedTicks.ToString()); Console.Write("Press any key to continue . . . "); Console.ReadKey(true); } } } 输出结果如下: 
|
2012年05月09日 11:37 前段时间折腾我的酷派8150,root成功之后,把移动的手机电视给删除了. 后来才想起来,我买手机的时候,是送话费的,而且送了6块钱的手机电视,于是没有办法,就把手机电视给装上了。可是,怎么弄也开通不了,因为手机电视列表上的后面,根本没有解锁的符号。 后来想起来了,是不是因为程序安装在sd卡的缘故,于是将手机电视安装到手机内存,然后就OK了。 所以,提醒使用酷派8150的亲们,要想开通手机电视功能,必须将手机电视软件安装到手机内存,切记。 |
2012年05月07日 8:23 这几天,不知道怎么搞的,双击excel文件的时候,总是不能打开,显示的是空白的,非要通过"文件"->'打开'才行,从网上找了下,结果是需要这样做的: 1 随便打开一个excel文件 2 '工具' -> '选项' -> '常规' -> 不选中' 忽略其他应用程序' 留下备忘~ |
2012年04月21日 15:47 最近在学习Linux的C编程,由于android系统的内核即为非标的linux内核,所以,就那程序到android系统上运行了一下,发现了struct passwd*结构体中的gecos成员,已经被android阉割掉了,不过,还好只阉割了这一个,其他的都保留了,程序如下: #include <unistd.h> #include <pwd.h> #include <sys/types.h> #include <stdio.h> int main(int argc,char* argv[]) { pid_t my_pid,parent_pid; uid_t my_uid,my_euid; gid_t my_gid,my_egid; struct passwd* my_info; my_pid=getpid(); parent_pid=getppid(); my_uid=getuid(); my_euid=geteuid(); my_gid=getgid(); my_egid=getegid(); my_info=getpwuid(my_uid); printf("Process ID: %ld\n",my_pid); printf("Parent ID: %ld\n",parent_pid); printf("User ID: %ld\n",my_uid); printf("Effective User ID: %ld\n",my_euid); printf("Group ID: %ld\n",my_gid); printf("Effective Group ID: %ld\n",my_egid); if(my_info){ printf("My Login Name: %s\n",my_info->pw_name); printf("My Password: %s\n",my_info->pw_passwd); printf("My User ID: %ld\n",my_info->pw_uid); printf("My Group ID: %ld\n",my_info->pw_gid); //printf("My Real Name: %s\n",my_info->pw_gecos); printf("My Home Dir: %s\n",my_info->pw_dir); printf("My Work Shell: %s\n",my_info->pw_shell); } return 0; } Android.mk的内容如下: LOCAL_PATH:=$(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE:=getpid-test LOCAL_SRC_FILES:=getpid-test.c include $(BUILD_EXECUTABLE) 之后,切换到工程目录下,使用ndk-build -B进行编译就可以了,我的是: 
然后,将工程目录下的libs文件夹下面的getpid-test拷贝到sd卡中,之后进入终端模拟器,使用root权限,将getpid-test拷贝到/data/data中,然后,运行即可.
|
2012年04月20日 15:24 很早之前我有一篇文章,用C语言编写了一个计算器:http://hi.baidu.com/pengjun/blog/item/21ce574e71331f16b2de0542.html 这个月14号呢,我buy了一个coolpad 8150,于是乎,想把我用C语言写的计算器弄到android手机上,这样手机上也可以用呀,多好,呵呵~ 经过将近一天的折腾,终于算是搞定了,呵呵......,步骤是这样的: 1 安装android软件: 终端模拟器 安装之后,进入这个软件,就相当于直接进入了android的linux命令行了,什么ls/cd/pwd/su/mv等linux的命令都可以执行的. 可以在豌豆荚直接搜索"终端模拟器"即可. 2 使用android ndk来对之前的C程序进行编译(注意,不需要做任何的更改哦) 当然,要想用android ndk来编译一个C程序为一个可以让android系统执行的程序,需要按照ndk的要求来. 第一步,新建一个目录calculator,并在其下创建jni目录,在jni目录下面,放入calculator.c(见文章第一行),并编写Android.mk文件,内容如下: LOCAL_PATH:=$(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE:=calculator LOCAL_SRC_FILES:=calculator.c include $(BUILD_EXECUTABLE) 第二步,打开ndk的命令行,进入calculator目录,输入ndk-build -B NDK_PROJECT_PATH=.命令,可以看到编译生成了一个可执行程序calculator. 第三步,将手机进入大容量存储模式,目的就是将calculator拷贝到SD卡里面 3 打开终端模拟器,输入su root命令,从而获得最高权限.当然,如果你的酷派8150还没有活得root权限,可以使用腾讯的应用助手等工具获取即可. 注意:必须活得root权限,不然不能执行编译成的程序的. 4 剩下来的工作,主要就是将calculator拷贝到除SD卡目录之外的目录下面,然后执行. 我是在系统的data目录下面新建了一个dev目录,然后将calculator从sd卡拷贝到dev目录,然后使用chmod 777 calculator命令来更改calculator文件的属性. 最后,使用root权限,执行calculator就可以了. 在android虚拟机的shell上的截图如下: 
所以,看来C程序还是有很大的优势的,只要使用的是标准的C库,程序直接编译后,便可在android手机上运行了. |
2012年04月14日 12:04 1 下载android SDK,网址:http://developer.android.com/sdk/index.html,根据系统的不同,选择不同的版本下载. 下载之后,直接解压. 运行SDK manager,选择需要的API版本进行安装. 
2 下载NDK,网址:http://developer.android.com/sdk/ndk/index.html,根据操作系统的不同,下载不同的版本. Windows版本的下载之后,解压即可使用. 3 下载Apache Ant,网址:http://ant.apache.org/bindownload.cgi,windows版本的下载zip格式的,解压即可使用. 4 安装JDK,下载地址从网上搜索就行了,之后需要通过"我的电脑"->"属性"->"高级"->"环境变量",来新建一个JAVA_HOME的环境变量,指向JDK的目录,如下: 
5 运行AVD Manager,创建一个虚拟的android,并点击start进行启动. 
6 在NDK的目录下,创建一个批处理文件android-cmd.bat,内容如下: set PATH=%PATH%;%cd%;I:\android\apache-ant-1.8.3\bin;D:\DevelopTools\android-sdk\platform-tools;D:\DevelopTools\android-sdk\tools;D:\DevelopTools\JDK7\bin; cmd.exe 从上面的内容可以看出,我的ant安装在I:\android\下面,android的sdk安装在D:\DevelopTools下面,JDK安装在D:\DevelopTools下面. 原因是,编译时需要用到ant/adb/android命令,所以需要将包含该命令的目录添加到该批处理的路径中.而ant需要JDK环境. 7 运行android-cmd.bat,使用cd命令切换到samples/hello-jni目录下, 运行android update project -p . -s,会生成build.xml文件,用于ant命令,要注意的是,编译的时候会发生错误,提示: Error: The project either has no target set or the target is invalid. Please provide a --target to the 'android.bat update' command. 这个时候,可以使用android list targets命令来查看当前系统中的android模拟器,我有两个,如下: I:\android\android-ndk-r7c\samples\native-activity>android.bat list targets Available Android targets: ---------- id: 1 or "android-8" Name: Android 2.2 Type: Platform API level: 8 Revision: 1 Skins: HVGA, QVGA, WQVGA400, WQVGA432, WVGA800 (default), WVGA854 ABIs : armeabi ---------- id: 2 or "android-10" Name: Android 2.3.3 Type: Platform API level: 10 Revision: 2 Skins: HVGA, QVGA, WQVGA400, WQVGA432, WVGA800 (default), WVGA854 ABIs : armeabi 如果没有的话,需要使用SDK的AVD Manager来创建一个就可以了.而我使用的是android 2.3.3的模拟器,所以我的编译命令是: I:\android\android-ndk-r7c\samples\native-activity>android update project -p . - t android-10 -s Updated and renamed default.properties to project.properties Updated local.properties No project name specified, using Activity name 'NativeActivity'. If you wish to change it, edit the first line of build.xml. Added file I:\android\android-ndk-r7c\samples\native-activity\build.xml Added file I:\android\android-ndk-r7c\samples\native-activity\proguard.cfg 从上面看出,已经生成了build.xml文件了. 运行ant debug命令,输出如下: I:\android\android-ndk-r7c\samples\hello-jni>ant debug Buildfile: I:\android\android-ndk-r7c\samples\hello-jni\build.xml -set-mode-check: -set-debug-files: -set-debug-mode: -debug-obfuscation-check: -setup: [echo] Gathering info for HelloJni... [setup] Android SDK Tools Revision 16 [setup] Project Target: Android 2.2 [setup] API level: 8 [setup] [setup] ------------------ [setup] Resolving library dependencies: [setup] No library dependencies. [setup] [setup] ------------------ [setup] [setup] WARNING: Attribute minSdkVersion in AndroidManifest.xml (3) is lower than the project target API level (8) -build-setup: [echo] Creating output directories if needed... -pre-build: -code-gen: [echo] ---------- [echo] Handling aidl files... [aidl] No AIDL files to compile. [echo] ---------- [echo] Handling RenderScript files... [renderscript] No RenderScript files to compile. [echo] ---------- [echo] Handling Resources... [aapt] Found Deleted Target File [aapt] Generating resource IDs... -pre-compile: -compile: [javac] Compiling 2 source files to I:\android\android-ndk-r7c\samples\hello -jni\bin\classes -post-compile: -obfuscate: -dex: [dex] Converting compiled files and external libraries into I:\android\and roid-ndk-r7c\samples\hello-jni\bin\classes.dex... -crunch: [crunch] Crunching PNG Files in source dir: I:\android\android-ndk-r7c\sample s\hello-jni\res [crunch] To destination dir: I:\android\android-ndk-r7c\samples\hello-jni\bin \res [crunch] Crunched 0 PNG files to update cache -package-resources: [aapt] Creating full resource package... [aapt] Warning: AndroidManifest.xml already defines debuggable (inhttp://s chemas.android.com/apk/res/android); using existing value in manifest. -package: [apkbuilder] Current build type is different than previous build: forced apkbuil der run. [apkbuilder] Creating HelloJni-debug-unaligned.apk and signing it with a debug k ey... -do-debug: [zipalign] Running zip align on final apk... [echo] Debug Package: I:\android\android-ndk-r7c\samples\hello-jni\bin\Hell oJni-debug.apk debug: [propertyfile] Creating new property file: I:\android\android-ndk-r7c\samples\he llo-jni\bin\build.prop [propertyfile] Updating property file: I:\android\android-ndk-r7c\samples\hello- jni\bin\build.prop [propertyfile] Updating property file: I:\android\android-ndk-r7c\samples\hello- jni\bin\build.prop [propertyfile] Updating property file: I:\android\android-ndk-r7c\samples\hello- jni\bin\build.prop BUILD SUCCESSFUL Total time: 5 seconds 从上面,可以看出,生成了HelloJni-debug.apk,那么使用adb命令安装到当前的虚拟机上就可以了. 运行adb install bin/HelloJni-debug.apk命令,如果出现:error: device not found,说明你的android模拟器尚未start. 运行后,出现如下提示: 185 KB/s (85934 bytes in 0.453s) pkg: /data/local/tmp/HelloJni-debug.apk Success 说明该apk,已经安装到android模拟器上了,单击模拟器上的主页按钮,可以看到HelloJni程序已经有了.如下:  点击HelloJni,进入程序,可以看到:

恭喜你,大功告成,收工!
|
2012年04月12日 9:53 近段时间,偶尔闲暇,会单机玩下DOTA(窗口模式的),但是每次玩都要打开魔兽,然后按S开始单机,然后按G开始自定义游戏,然后选择9个AI的疯狂,然后按S开始游戏,进入游戏之后,每次都输入模式-arakfefnul,总觉得厌烦. 所以,就用C语言来模拟鼠标和键盘操作实现这些操作就可以了,顺便再游戏中也可以限制下鼠标,避免鼠标飘出游戏窗口. 原理很简单: 模拟按键和鼠标点击就不说了,直接使用keybd_event和mouse_event函数就可以了. 而选择AI对手的时候,需要知道鼠标的位置,这个只要观察下,找出其中合适的间距就行了. 而且,点击位置相对于游戏窗口的位置也是不变的. 下面是完整的程序,可以根据需要对延时的时间进行控制. #include <stdio.h> #include <stdlib.h> #include <windows.h> #define CURSOR_TO_LEFT_WIN 275 #define CURSOR_TO_UP_WIN 265 RECT rectWar3Win; void mouse_lpress(void) { mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP,0,0,0,0); } void keybd_press(char key_code) { keybd_event(key_code,0,0,0); //down Sleep(50); keybd_event(key_code,0,2,0); //up } void move_cursor(int offset_left,int offset_up) { SetCursorPos(rectWar3Win.left+CURSOR_TO_LEFT_WIN+offset_left, rectWar3Win.top+CURSOR_TO_UP_WIN+offset_up); } void choose_up_ai(int id) { Sleep(200); move_cursor(0,25*id); Sleep(200); mouse_lpress(); Sleep(200); move_cursor(0,88+25*id); Sleep(200); mouse_lpress(); } void choose_dn_ai(int id) { Sleep(200); move_cursor(0,25*id+110); Sleep(200); mouse_lpress(); Sleep(200); move_cursor(0,88+25*id+110); Sleep(200); mouse_lpress(); } int main() { HWND hWar3Win=NULL; int i=0; HWND temp=NULL; HWND to_find=NULL; system("\"F:\\Warcraft\\Frozen Throne.exe\" -windows"); while(hWar3Win==NULL){ hWar3Win=FindWindow(NULL,"Warcraft III"); Sleep(50); } SetForegroundWindow(hWar3Win); GetWindowRect(hWar3Win,&rectWar3Win); Sleep(3000); keybd_press('S'); Sleep(3000); keybd_press('G'); Sleep(4000); for(i=0;i<4;i++) { choose_up_ai(i); } for(i=0;i<5;i++) { choose_dn_ai(i); } keybd_press('S'); Sleep(7000); keybd_press('S'); Sleep(3000); keybd_press(VK_RETURN); Sleep(1000); keybd_press(VK_RETURN); Sleep(1000); keybd_press(VK_SUBTRACT); Sleep(1000); keybd_press('A'); Sleep(100); keybd_press('R'); Sleep(100); keybd_press('A'); Sleep(100); keybd_press('K'); Sleep(100); keybd_press('F'); Sleep(100); keybd_press('E'); Sleep(100); keybd_press('F'); Sleep(100); keybd_press('N'); Sleep(100); keybd_press('U'); Sleep(100); keybd_press('L'); Sleep(100); keybd_press(VK_RETURN); Sleep(100); while(1){ temp=GetForegroundWindow(); to_find=FindWindow(NULL,"Warcraft III"); if(temp==to_find){ if(GetWindowRect(to_find,&rectWar3Win)){ rectWar3Win.bottom -= 5; rectWar3Win.left += 5; rectWar3Win.right -= 5; rectWar3Win.top += 32; ClipCursor(&rectWar3Win); } }else{ ClipCursor(NULL); } if(to_find==NULL) break; Sleep(100); } return 0; }
|
2012年03月31日 9:47 I think we always use the string type, so it's best to create a file to implement the usual functions, like is_contain,sub_str,replace_str, and something like that. OK, let's just look the code. ---------------------------------------------------c_str.h------------------------------------------------- #ifndef C_STR_H_INCLUDED #define C_STR_H_INCLUDED
extern int cstr_length(const char* str); extern int cstr_is_contain(const char* str, char to_find); extern int cstr_find_first(const char* str, char to_find); extern int cstr_find_last(const char* str, char to_find); extern int cstr_find_all(const char* str, char to_find, int* pos);
extern void cstr_set_zero(char* str,int length); extern void cstr_cat(char* dst, const char* src); extern void cstr_copy_to(char* dst, const char* src); extern void cstr_replace_char(char* str, int rep_pos, char rep_char); extern void cstr_replace_str(char* str, int rep_pos, const char* rep_str); extern void cstr_sub_str(char* sub_str,char* str,int start_pos,int length);
#endif // C_STR_H_INCLUDED ----------------------------------------------------------c_str.c----------------------------------------------------------- #include <stdlib.h>
#include "c_str.h"
int cstr_length(const char* str){ char* p=(char*)str; int p_count=0;
while(*p!='\0'){ p_count++; p++; }
return p_count; }
int cstr_is_contain(const char* str, char to_find){ char* p=(char*)str;
while(*p!='\0'){ if(*p==to_find) return 1; p++; } return 0; }
int cstr_find_first(const char* str, char to_find){ char* p=(char*)str; int pos=0;
while(*p!='\0'){ if(*p==to_find) return pos; pos++; p++; }
return pos; }
int cstr_find_last(const char* str, char to_find){ char* p=(char*)str; int pos=0; int last_pos=0;
while(*p!='\0'){ if(*p==to_find){ last_pos=pos; }
pos++; p++; }
return last_pos; }
int cstr_find_all(const char* str, char to_find, int* pos){ char* p=(char*)str; int* pp=pos; int p_pos=0; int p_count=0;
while(*p!='\0'){ if(*p==to_find){ *pp=p_pos; pp++; p_count++; }
p_pos++; p++; }
return p_count; }
void cstr_copy_to(char* dst, const char* src){ char* p_src=(char*)src; char* p_dst=dst;
while(*p_src!='\0'){ *p_dst=*p_src; p_dst++; p_src++; }
*p_dst='\0'; }
void cstr_cat(char* dst, const char* src){ int dst_len=cstr_length(dst); int src_len=cstr_length(src); char* temp=(char*)malloc(sizeof(char)*dst_len); char* p_dst=dst; char* p_src=(char*)src;
cstr_copy_to(temp,dst); realloc(dst,sizeof(char)*(dst_len+src_len)); p_dst=dst;
while(*temp!='\0'){ *p_dst=*temp;
p_dst++; temp++; }
while(*p_src!='\0'){ *p_dst=*p_src;
p_dst++; p_src++; }
*p_dst='\0';
free(temp); temp=0; }
void cstr_replace_char(char* str, int rep_pos, char rep_char){ char* p=str; int pos=0;
while(*p!='\0'){ if(pos==rep_pos){ *p=rep_char; return; }
p++; pos++; } }
void cstr_replace_str(char* str, int rep_pos, const char* rep_str){ int str_len=cstr_length(str); int rep_len=cstr_length(rep_str); char* p=str; char* temp=(char*)malloc(sizeof(char)*str_len); char* rep=(char*)rep_str; char* p_temp=temp; int p_pos=0;
cstr_copy_to(temp,str);
if((str_len-rep_pos)<rep_len){ realloc(str,sizeof(char)*(str_len-rep_pos+rep_len+1)); p=str; }
while(*p_temp!='\0'){ if(p_pos==rep_pos){ while(*rep!='\0'){ *p=*rep; rep++; p++; p_temp++; p_pos++; } }
*p=*p_temp; p++; p_temp++; p_pos++; }
*p='\0';
free(temp); temp=0; }
void cstr_sub_str(char* sub_str,char* str,int start_pos,int length){ char* p_sub=sub_str; char* p_str=str; int p_pos=0; int sub_len=0;
while(*p_str!='\0'){ if(p_pos==start_pos){ while(sub_len!=length){ *p_sub=*p_str; p_str++; p_sub++; sub_len++; } break; }
p_str++; p_pos++; }
*p_sub='\0'; }
void cstr_set_zero(char* str,int length){ char* p=str; int p_pos=0;
while(p_pos<length){ *p='\0'; p++; p_pos++; } }
-------------------------------------------------------------main.c-------------------------------------------------------- #include <stdio.h> #include <stdlib.h> #include <string.h>
#include "c_str.h"
int main() { char* str="971231451abcde1f"; int* ch_pos=(int*)malloc(sizeof(int)*cstr_length(str)); int ch_num=0; int i=0; char* str_cpy=(char*)malloc(sizeof(char)*cstr_length(str)); char* str2=(char*)malloc(sizeof(char)*4); char* sub_str=(char*)malloc(sizeof(char)*5);
str2[0]='+'; str2[1]='-'; str2[2]='*'; str2[3]='/'; str2[4]='\0';
printf("str: %s\r\n",str); printf("length: %d\r\n",cstr_length(str)); printf("is_contain: %d\r\n",cstr_is_contain(str,'a')); printf("is_contain: %d\r\n",cstr_is_contain(str,'g')); printf("find_first: %d\r\n",cstr_find_first(str,'1')); printf("find_last: %d\r\n",cstr_find_last(str,'1'));
printf("find_all: "); ch_num=cstr_find_all(str,'1',ch_pos); for(i=0;i<ch_num;i++){ printf("%d ",ch_pos[i]); } printf("\r\n");
cstr_copy_to(str_cpy,str); printf("copy_to: %s\r\n",str_cpy);
printf("str2: %s\r\n",str2); cstr_cat(str2,"abcd90090909"); printf("cat: %s\r\n",str2);
cstr_replace_char(str2,2,'&'); printf("replace_ch: %s\r\n",str2);
cstr_replace_str(str2,4,"*1234"); printf("replace_str:%s\r\n",str2);
cstr_replace_str(str2,14,"*1234"); printf("replace_str:%s\r\n",str2);
cstr_sub_str(sub_str,str2,2,5); printf("sub_str: %s\r\n",sub_str);
free(ch_pos); ch_pos=0;
free(str_cpy); str_cpy=0;
free(str2); str2=0;
free(sub_str); sub_str=0;
return 0; } ---------------------------------------------------------------result---------------------------------------------------------- 
|
2012年03月27日 10:14 之前,一想到要写串口程序,肯定首先想到的就是VB/C#之类的,因为在这些语言里面只要拉个控件,设置下参数就可以了. 但是, 最近又对C语言来了兴趣,所以,在网上看到一篇用C++写的串口类. 于是,我就将它基本上是抄写下来了, 编程了C可用的.如下: //////////////////////////serial_port.h////////////////////// #ifndef SERIAL_PORT_H_INCLUDED #define SERIAL_PORT_H_INCLUDED
#include <windows.h> #include <tchar.h>
#define TIMEOUT_READ_INTERVAL 0xFFFFFFFF #define TIMEOUT_READ_TOTAL_MULTIPLIER 0 #define TIMEOUT_READ_TOTAL_CONSTANT 0
#define TIMEOUT_WRITE_TOTAL_MULTIPLIER 0 #define TIMEOUT_WRITE_TOTAL_CONSTANT 0
#define BUFFER_INPUT_RECOMMEND 10000 #define BUFFER_OUTPUT_RECOMMEND 10000
#define TIMEOUT_READCOMM_EVENT 4000 #define TIMEOUT_WRITECOMM_EVENT 2000
#define FC_DTRDSR 0x01 #define FC_RTSCTS 0x02 #define FC_XONXOFF 0x04 #define ASCII_BEL 0x07 #define ASCII_BS 0x08 #define ASCII_LF 0x0A #define ASCII_CR 0x0D #define ASCII_XON 0x11 #define ASCII_XOFF 0x13
#define SP_ONE_STOPBIT 0 #define SP_ONE5_STOPBITS 1 #define SP_TWO_STOPBITS 2
#define SP_NO_PARITY 0 #define SP_ODD_PARITY 1 #define SP_EVEN_PARITY 2 #define SP_MARK_PARITY 3 #define SP_SPACE_PARITY 4
extern HANDLE sp_hIDComDev; extern OVERLAPPED sp_overlappedRead; extern OVERLAPPED sp_overlappedWrite; extern int sp_isOpened;
extern void sp_Initialize(void); extern int sp_OpenPort(int port, int baud_rate,int parity,int data_bits,int stop_bits); extern int sp_ClosePort(void);
extern int sp_ReadData(void* data, int length); extern int sp_WriteData(const char* data, int length); extern int sp_BytesToRead(void); extern int sp_IsOpened(void); extern int sp_WriteChar(char ch);
#endif // SERIAL_PORT_H_INCLUDED
///////////////////////////serial_port.c///////////////////////////// #include "serial_port.h"
HANDLE sp_hIDComDev; OVERLAPPED sp_overlappedRead; OVERLAPPED sp_overlappedWrite; int sp_isOpened;
void sp_Initialize(void){ memset(&sp_overlappedRead,0,sizeof(OVERLAPPED)); memset(&sp_overlappedWrite,0,sizeof(OVERLAPPED));
sp_hIDComDev=NULL; sp_isOpened=0; }
int sp_OpenPort(int port, int baud_rate,int parity,int data_bits,int stop_bits){ TCHAR szPort[50]; DCB dcb; COMMTIMEOUTS CommTimeOuts; unsigned char ucSet; DWORD dwError;
if(sp_isOpened) return 1;
wsprintf(szPort,_T("COM%d"),port); sp_hIDComDev=CreateFile(szPort, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL); if(!sp_hIDComDev) return 0;
CommTimeOuts.ReadIntervalTimeout=TIMEOUT_READ_INTERVAL; CommTimeOuts.ReadTotalTimeoutMultiplier=TIMEOUT_READ_TOTAL_MULTIPLIER; CommTimeOuts.ReadTotalTimeoutConstant=TIMEOUT_READ_TOTAL_CONSTANT; CommTimeOuts.WriteTotalTimeoutMultiplier=TIMEOUT_WRITE_TOTAL_MULTIPLIER; CommTimeOuts.WriteTotalTimeoutConstant=TIMEOUT_WRITE_TOTAL_CONSTANT; SetCommTimeouts(sp_hIDComDev,&CommTimeOuts);
sp_overlappedRead.hEvent=CreateEvent(NULL,1,0,NULL); sp_overlappedWrite.hEvent=CreateEvent(NULL,1,0,NULL);
dcb.DCBlength=sizeof(DCB); GetCommState(sp_hIDComDev,&dcb); dcb.BaudRate=baud_rate; dcb.ByteSize=data_bits; dcb.StopBits=stop_bits; dcb.Parity=parity;
ucSet=(unsigned char)((FC_RTSCTS & FC_DTRDSR)!=0); ucSet=(unsigned char)((FC_RTSCTS & FC_RTSCTS)!=0); ucSet=(unsigned char)((FC_RTSCTS & FC_XONXOFF)!=0);
if(!SetCommState(sp_hIDComDev,&dcb) || !SetupComm(sp_hIDComDev,BUFFER_INPUT_RECOMMEND,BUFFER_OUTPUT_RECOMMEND) || sp_overlappedRead.hEvent==NULL || sp_overlappedWrite.hEvent==NULL){ dwError=GetLastError();
if(sp_overlappedRead.hEvent!=NULL) CloseHandle(sp_overlappedRead.hEvent);
if(sp_overlappedWrite.hEvent!=NULL) CloseHandle(sp_overlappedWrite.hEvent);
CloseHandle(sp_hIDComDev); return 0; }
sp_isOpened=1; return 1; }
int sp_ClosePort(void){ if(!sp_isOpened || sp_hIDComDev==NULL) return 1;
if(sp_overlappedRead.hEvent!=NULL) CloseHandle(sp_overlappedRead.hEvent);
if(sp_overlappedWrite.hEvent!=NULL) CloseHandle(sp_overlappedWrite.hEvent);
CloseHandle(sp_hIDComDev);
sp_hIDComDev=NULL; sp_isOpened=0;
return 1; }
int sp_IsOpened(void){ return sp_isOpened; }
int sp_WriteChar(char ch){ int bWriteStat; DWORD dwBytesWritten;
bWriteStat=WriteFile(sp_hIDComDev,(LPSTR)&ch,1,&dwBytesWritten,&sp_overlappedWrite);
if(!bWriteStat && (GetLastError()==ERROR_IO_PENDING)){ if(WaitForSingleObject(sp_overlappedWrite.hEvent,TIMEOUT_WRITECOMM_EVENT)){ dwBytesWritten=0; }else{ GetOverlappedResult(sp_hIDComDev,&sp_overlappedWrite,&dwBytesWritten,0); sp_overlappedWrite.Offset+=dwBytesWritten; } }
return 1; }
int sp_WriteData(const char* data, int length){ DWORD dwBytesWritten=0; char* p=(char*)data;
if(!sp_isOpened || sp_hIDComDev==NULL) return 0;
while(*p!='\0'){ sp_WriteChar(*p);
p++; dwBytesWritten++; }
return dwBytesWritten; }
int sp_BytesToRead(void){ DWORD dwErrorFlags; COMSTAT ComStat;
if(!sp_isOpened || sp_hIDComDev==NULL) return 0;
ClearCommError(sp_hIDComDev,&dwErrorFlags,&ComStat);
return ComStat.cbInQue; }
int sp_ReadData(void* data, int length){ int bReadStatus; DWORD dwBytesRead,dwErrorFlags; COMSTAT ComStat;
if(!sp_isOpened || sp_hIDComDev==NULL) return 0;
ClearCommError(sp_hIDComDev,&dwErrorFlags,&ComStat);
if(!ComStat.cbInQue) return 0;
dwBytesRead=(DWORD)ComStat.cbInQue;
if(length<(int)dwBytesRead) dwBytesRead=(DWORD)length;
bReadStatus=ReadFile(sp_hIDComDev,data,dwBytesRead,&dwBytesRead,&sp_overlappedRead);
if(!bReadStatus){ if(GetLastError()==ERROR_IO_PENDING){ WaitForSingleObject(sp_overlappedRead.hEvent,TIMEOUT_READCOMM_EVENT); return dwBytesRead; }
return 0; }
return dwBytesRead; }
//////////////////////////main.c////////////////////////////
#include <stdio.h> #include <stdlib.h>
#include "serial_port.h"
int main(int argc,char* argv[]) { char ch=0;
if(argc!=6){ printf("Usage: comm <port> <baud_rate> <parity> <data_bits> <stop_bits>\r\n"); printf("\tParity: \r\n"); printf("\t 0-No parity\r\n"); printf("\t 1-Odd parity\r\n"); printf("\t 2-Even parity\r\n"); printf("\t 3-Mark parity\r\n"); printf("\t 4-Space parity\r\n"); printf("\tStopBits:\r\n"); printf("\t 0-one stop bit\r\n"); printf("\t 1-one point 5 stop bits\r\n"); printf("\t 2-two stop bits\r\n"); printf("\tDataBits: range is 4~8\r\n"); return -1; }
if(sp_OpenPort(atoi(argv[1]),atoi(argv[2]),atoi(argv[3]),atoi(argv[4]),atoi(argv[5]))) printf("open com1 passed.\r\n"); else printf("open com1 failed.\r\n");
while(1){ if(sp_BytesToRead()>0){ sp_ReadData(&ch,1); printf("%c",ch); }
Sleep(10); }
if(sp_IsOpened()) sp_ClosePort();
return 0; }
用起来还是感觉很爽的,呵呵~ |
2012年03月24日 17:02 AML8726-H芯片的直接输出tvout的公版程序中,有一个音频BUG:第一次开机,调节音量时,若调整到静音,会直接变为音量最大. 造成此BUG存在,主要是uSysParm控件中的Volume没有初始化,直接使用这句进行初始化就可以了.如下: 在system页面的Init消息中: 
编辑环境使用的是AframeMaker.
|
2012年03月23日 15:43 最近,我们做的一个LED投影机的MP4在播放tiff格式的图片时,总是提示图片格式不支持.后来,才发现原来Windows自带的图片查看器,在另存为的时候,对图片进行了压缩,才导致了AML8726-H芯片对TIFF图片不能解码. 后来使用Photoshop或ACDSee等工具另存为一下就好了.特别要说的,还是Photoshop,在另存为的时候会提示你做选择.虽然ACDSee没有提示,但是默认的是无压缩的. 因此,只有无压缩的TIFF图片才能被AML8726-H芯片所解码. 所以呢,我就用了FreeImage来写了一个简单的图片格式转换程序. 全部程序如下: #include <stdio.h> #include <stdlib.h>
#include <string.h>
#include "FreeImage.h"
#ifndef MAX_PATH #define MAX_PATH 260 #endif
void FreeImageErrorHandler(FREE_IMAGE_FORMAT fif, const char *message) { printf("\n*** "); if(fif != FIF_UNKNOWN) { printf("%s Format: ", FreeImage_GetFormatFromFIF(fif)); } printf(message); printf(" ***\n"); }
int main(int argc,char* argv[]) { FREE_IMAGE_FORMAT fif=FIF_UNKNOWN; FIBITMAP *dib=NULL; char* new_path=(char*)malloc(sizeof(char)*MAX_PATH); int bpp=0; char* p=NULL; char* q=NULL;
if(argc!=3){ printf("Usage: imgfmtcvt <dst_fmt> <file_path>\r\n"); return 0; }
//construct the new file path memset(new_path,0,sizeof(char)*MAX_PATH); for(p=argv[2],q=new_path;p!='\0';p++,q++){ if(*p!='.'){ *q=*p; }else{ *q=*p; break; } } strcat(new_path,argv[1]); printf("new path: %s\r\n",new_path);
FreeImage_Initialise(FALSE); FreeImage_SetOutputMessage(FreeImageErrorHandler);
//load the src image fif=FreeImage_GetFileType(argv[2],0); if(fif==FIF_UNKNOWN){ fif=FreeImage_GetFIFFromFilename(argv[2]); }
if((fif!=FIF_UNKNOWN) && FreeImage_FIFSupportsReading(fif)){ dib=FreeImage_Load(fif,argv[2],0); if(dib){ fif=FreeImage_GetFIFFromFilename(new_path); if(fif!=FIF_UNKNOWN){ bpp=FreeImage_GetBPP(dib); if(FreeImage_FIFSupportsWriting(fif) && FreeImage_FIFSupportsExportBPP(fif,bpp)){ if(FreeImage_Save(fif,dib,new_path,TIFF_NONE)){ printf("*****convert passed.\r\n"); }else{ printf("ERROR: convert failed.\r\n"); } }else{ printf("ERROR: not support writing or not support exports BPP.\r\n"); } }else{ printf("ERROR: unknown file type.\r\n"); } }else{ printf("ERROR: load the image failed.\r\n"); } }else{ printf("ERROR: unsupported image format or not support reading.\r\n"); }
FreeImage_Unload(dib);
FreeImage_DeInitialise();
free(new_path);
return 0; } 我使用Codeblock写的,可以到FreeImage的网站去下载h文件/dll文件和lib文件.将h和dll文件拷贝到工程目录,将lib文件添加到编译环境的library中就ok了. |
| | |