Home Php C# Sql C C++ Javascript Python Java Go Android Git Linux Asp.net Django .net Node.js Ios Xcode Cocoa Iphone Mysql Tomcat Mongodb Bash Objective-c Scala Visual-studio Apache Elasticsearch Jar Eclipse Jquery Ruby-on-rails Ruby Rubygems Android-studio Spring Lua Sqlite Emacs Ubuntu Perl Docker Swift Amazon-web-services Svn Html Ajax Xml Java-ee Maven Intellij-idea Rvm Macos Unix Css Ipad Postgresql Css3 Json Windows-server Vue.js Typescript Oracle Hibernate Internet-explorer Github Tensorflow Laravel Symfony Redis Html5 Google-app-engine Nginx Firefox Sqlalchemy Lucene Erlang Flask Vim Solr Webview Facebook Zend-framework Virtualenv Nosql Ide Twitter Safari Flutter Bundle Phonegap Centos Sphinx Actionscript Tornado Register | Login | Edit Tags | New Questions | 繁体 | 简体


10 questions online user: 8

0
votes
answers
15 views
+10

如何在文本框旁邊顯示tooltil?

-1

我有一個工具提示TextBox。如何在文本框旁邊顯示tooltil?

我需要在我的文本框旁邊顯示工具提示,但怎麼做?

if (this.txtBoxName.Text == "") 

{ 
    ToolTip tip = new ToolTip(); 
    tip.IsBalloon = false; 
    tip.ToolTipTitle = ""; 
    tip.InitialDelay = 0; 
    tip.BackColor = Color.Aqua; 
    this.txtBoxName.Focus(); 
    Point point = new Point(750, 560); 
    tip.Show("Please Enter UserName", this.txtBoxName); 
} 
+0

參見:[展會上的文本框進入提示](HTTPS ://stackoverflow.com/questions/14695357/show-tooltip-on-textbox-entry)。 –

+0

你必須設置你的點x,y相對於你的文本框。 – aghilpro

+0

請爲此使用佔位符文本而不是工具提示。 –

沙发
0
1

試試這個:

if (this.txtBoxName.Text == null || this.txtBoxName.Text == "") 
{ 
    ToolTip tip = new ToolTip(); 
    tip.IsBalloon = false; 
    tip.ToolTipTitle = ""; 
    tip.InitialDelay = 0; 
    tip.BackColor = Color.Aqua; 
    this.txtBoxName.Focus(); 
    Point point = new Point(txtBoxName.Location.X - 50, txtBoxName.Location.Y - 50); // for example 50px change 
    tip.Show("Please Enter UserName", this.txtBoxName, point, 2000); // set 2000ms to auto close TooTip 
} 

我用這個Show功能overLoad,看到有關它的詳細信息:

public void Show(string text, IWin32Window window, Point point, int duration);

摘要: 設置與指定控件關聯的工具提示文本,然後>在指定的相對位置顯示指定持續時間的工具提示 。

參數

文本: 一個包含新的工具提示文本System.String。

窗口: 顯示工具提示的System.Windows.Forms.Control。

: 甲System.Drawing.Point含有的偏移量,以像素爲單位,相對於該相關聯的控制窗口的 左上角,以顯示工具提示。

持續時間:含有 一個System.Int32的持續時間,以毫秒爲單位,以顯示 工具提示。

例外

System.ArgumentNullException: 窗口參數爲null。

System.ArgumentOutOfRangeException: 持續時間小於或等於0

+0

它的工作表示感謝。 :)) – comodor16

板凳
0
1

您還可以定義一個模板文本框

<TextBox.Template> 
    <ControlTemplate> 
     <StackPanel Orientation="Horizontal"> 
      <TextBlock Text="{TemplateBinding ToolTip}" /> 
      <TextBox Text="{TemplateBinding TextBox.Text}"></TextBox> 
     </StackPanel> 
    </ControlTemplate> 
</TextBox.Template> 
+0

這很好。謝謝 – Skyuppercut

0
votes
answers
43 views
+10

基於HTTP動詞的路由動作?

0

我想基於在Startup.cs通過下面的代碼HTTP動詞得到ASP.NET的Core 2 MVC路由的行動:基於HTTP動詞的路由動作?

 app.UseMvc(routes => 
     { 
      routes.MapRoute(
       name: "post", 
       template: "api/{controller}/{id?}", 
       defaults: new { action = "Post" }, 
       constraints: new RouteValueDictionary(new { httpMethod = new HttpMethodRouteConstraint("POST") }) 
      ); 
      routes.MapRoute(
       name: "delete", 
       template: "api/{controller}/{id?}", 
       defaults: new { action = "Delete" }, 
       constraints: new RouteValueDictionary(new { httpMethod = new HttpMethodRouteConstraint("DELETE") }) 
      ); 
      routes.MapRoute(
       name: "default", 
       template: "api/{controller}/{action=Get}/{id?}"); 
     }); 

也就是說,

  • 如果客戶端請撥打GET http://example.com/api/foo,在我的FooController : Controller類上運行Get()方法。
  • 如果他們呼叫GET http://example.com/api/foo/123,那麼在我的FooController : Controller類上運行Get(int id)方法。
  • 如果他們呼叫POST http://example.com/api/foo,那麼在我的FooController<T> : Controller類上運行Post([FromBody] T postedItem)方法。
  • 如果他們呼叫POST http://example.com/api/foo/123,那麼在我的FooController<T> : Controller類上運行Post(int id, [FromBody] T postedItem)方法。
  • 如果他們叫DELETE http://example.com/api/foo/123,在運行Delete(int id)方法對我FooController : Controller

當我運行該項目,它似乎並沒有運行任何我的控制器。我有一些Razor頁面可以響應,但所有基於控制器的路由只返回404路由。即使默認路由似乎不起作用。

我一直在使用https://github.com/ardalis/AspNetCoreRouteDebugger試圖幫助我縮小問題的範圍,但我仍然沒有發現問題。它將控制器上的方法顯示爲可用操作,但未列出通過MapRoute添加的任何名稱,模板或約束。我很高興知道任何其他有用的工具。

FWIW,我試圖使用相同的動詞限制如下: https://github.com/aspnet/Routing/blob/2.0.1/src/Microsoft.AspNetCore.Routing/RequestDelegateRouteBuilderExtensions.cs#L252-L268

+0

什麼是'FooController的'?您無法直接路由到通用控制器,因爲Core在構建期間無法提供該類型。您可以將其用作基本控制器,但您必須路由到「實現」該類型的內容,即「BarController:FooControlller '。 –

+0

@ChrisPratt:這是一些僞代碼,旨在傳達各種控制器將期望不同的POST主體架構並接收各自類型的[FromBody]參數。我把把具體類型作爲方法參數一定沒問題 - 只是每個類都有相同的方法名稱,但期望不同的具體類型。附:我喜歡你的電影(也許你真的是克里斯普拉特?):https://www.youtube.com/embed/kj802AGE9Bg?start=22&end=25 – steamer25

沙发
0
0

所以我不記得到底是什麼問題原來是,但元的解決方案是,你可以調試路由通過將日誌級別從「信息」增加到「調試」來解決問題。例如,通過appsettings.json:

{ 
    "Logging": { 
    "Debug": { 
     "LogLevel": { 
     "Default": "Debug" 
     } 
    }, 
    "Console": { 
     "LogLevel": { 
     "Default": "Debug" 
     } 
    } 
    } 
} 

...然後你會得到這樣的例如,Visual Studio中的應用程序輸出窗格中的消息:

[40m[37mdbug[39m[22m[49m: Microsoft.AspNetCore.Routing.RouteConstraintMatcher[1] 
     Route value '(null)' with key 'httpMethod' did not match the constraint 'Microsoft.AspNetCore.Routing.Constraints.HttpMethodRouteConstraint'. 
Microsoft.AspNetCore.Routing.RouteConstraintMatcher:Debug: Route value '(null)' with key 'httpMethod' did not match the constraint 'Microsoft.AspNetCore.Routing.Constraints.HttpMethodRouteConstraint'. 
[40m[37mdbug[39m[22m[49m: Microsoft.AspNetCore.Routing.RouteBase[1] 
     Request successfully matched the route with name 'get' and template 'api/{controller}/{id?}'. 
Microsoft.AspNetCore.Routing.RouteBase:Debug: Request successfully matched the route with name 'get' and template 'api/{controller}/{id?}'. 
[40m[37mdbug[39m[22m[49m: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1] 
     Executing action Contoso.Media.ServiceHost.Controllers.MediaController.Get (Contoso.Media.ServiceHost) 
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Debug: Executing action Contoso.Media.ServiceHost.Controllers.MediaController.Get (Contoso.Media.ServiceHost) 
0
votes
answers
26 views
+10

如何調用一個過程,如果過程沒有參數

-2
create proc sp_dropdown 

as 
begin 

SELECT r1.regid, r.registration 
FROM table1 as r1 
INNER JOIN table2 as r ON r1.regid=r.registration and r1.status=r.status 
end 
+2

正如一個確實有參數,但沒有參數。閱讀[問]並分享你的研究成果。 – CodeCaster

沙发
0
0

這上面的類是我的SP返回類型,

public class GetAllTableNames_Result 
    { 
     public string Name { get; set; } 
    } 

,我可以把這個像

public List<GetAllTableNames_Result> GetTableNames() 
    { 
     List<GetAllTableNames_Result> gatnr = new List<GetAllTableNames_Result>(); 
     SqlCommand cmd = new SqlCommand(
      "GetAllTableNames", _connection) {CommandType = CommandType.StoredProcedure}; 
     try 
     { 
      _connection.Open(); 
      SqlDataReader rdr = cmd.ExecuteReader(); 
      while (rdr.Read()) 
      { 

        //do something with data 
       gatnr.Add(new GetAllTableNames_Result() 
       { 
        Name = rdr[0].ToString() 
       }); 

      } 
      _connection.Close(); 

      return gatnr; 
     } 
     catch (Exception e) 
     { 
      Console.WriteLine(e); 
      throw; 
     } 
     finally 
     { 
      _connection.Close(); 
     } 

    } 

我相信你可以得到點

329
votes
answers
32 views
+10

Why is JsonRequestBehavior needed?

Why is Json Request Behavior needed?

If I want to restrict the HttpGet requests to my action I can decorate the action with the [HttpPost] attribute

Example:

[HttpPost]
public JsonResult Foo()
{
    return Json("Secrets");
}

// Instead of:
public JsonResult Foo()
{
    return Json("Secrets", JsonRequestBehavior.AllowGet);
}

Why isn't [HttpPost]sufficient?
Why the framework "bugs" us with the JsonRequestBehavior.AllowGet for every JsonResult that we have. If I want to deny get requests I'll add the HttpPost attribute.

up vote 263 down vote accepted favorite
沙发
+2630
+50

MVC defaults to DenyGet to protect you against a very specific attack involving JSON requests to improve the liklihood that the implications of allowing HTTP GET exposure are considered in advance of allowing them to occur.

This is opposed to afterwards when it might be too late.

Note: If your action method does not return sensitive data, then it should be safe to allow the get.

Further reading from my Wrox ASP.NET MVC3 book

By default, the ASP.NET MVC framework does not allow you to respond to an HTTP GET request with a JSON payload. If you need to send JSON in response to a GET, you'll need to explicitly allow the behavior by using JsonRequestBehavior.AllowGet as the second parameter to the Json method. However, there is a chance a malicious user can gain access to the JSON payload through a process known as JSON Hijacking. You do not want to return sensitive information using JSON in a GET request. For more details, see Phil's post at http://haacked.com/archive/2009/06/24/json-hijacking.aspx/ or this SO post.

Haack, Phil (2011). Professional ASP.NET MVC 3 (Wrox Programmer to Programmer) (Kindle Locations 6014-6020). Wrox. Kindle Edition.

Related StackOverflow question

With most recents browsers (starting with Firefox 21, Chrome 27, or IE 10), this is no more a vulnerability.

我認為這已經足夠了。當您希望允許數據作為HttpGet的結果傳遞時,您只需要AllowGet。如果使用1參數調用Json(數據),則DenyGet是默認值。 - danludwig 2011年12月11日14:36

這是我的問題。為什麼框架使用JsonRequestBehavior.AllowGet為我所擁有的每個JsonResult“竊聽”我們。如果我想拒絕獲取請求,我將添加HttpPost屬性。 - gdoron 2011年12月11日14:38

我認為這是因為沒有很多人意識到這個不起眼的漏洞。你說如果你想拒絕這個請求,你會用[HttpPost]來做。然而,MVC作者正在為您提供一層防範此類攻擊的保護。由於您需要努力添加第二個參數,因此您應該花時間考慮要暴露的數據以及它的敏感程度。 - danludwig 2011年12月11日14:42

那麼現在我們混亂了我們的API並將動詞混淆添加到“RESTful”接口以繞過潛在的CLIENT驅動的漏洞?這看起來很可怕......但我很感激討論。 - Norman H 2013年4月30日19:34

+520

To make it easier for yourself you could also create an actionfilterattribute

public class AllowJsonGetAttribute : ActionFilterAttribute
{
    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        var jsonResult = filterContext.Result as JsonResult;

        if (jsonResult == null)
            throw new ArgumentException("Action does not return a JsonResult, 
                                                   attribute AllowJsonGet is not allowed");

        jsonResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;            

        base.OnResultExecuting(filterContext);
    }
}

and use it on your action

[AllowJsonGet]
public JsonResult MyAjaxAction()
{
    return Json("this is my test");
}

此外,您可以將其設置為RegisterGlobalFilters中的默認過濾器:filters.Add(new AllowJsonGetAttribute())。但是,您必須刪除Exception,因為Filter將應用於所有操作方法。 - Undercover1989 18年1月26日8:54

+70

By default Jsonresult "Deny get"

Suppose if we have method like below

  [HttpPost]
 public JsonResult amc(){}

By default it "Deny Get".

In the below method

public JsonResult amc(){}

When you need to allowget or use get ,we have to use JsonRequestBehavior.AllowGet.

public JsonResult amc()
{
 return Json(new Modle.JsonResponseData { Status = flag, Message = msg, Html = html }, JsonRequestBehavior.AllowGet);
}

對不起它沒有回答這個問題... - gdoron 12月1日在18:34

+50

Improving upon the answer of @Arjen de Mooij a bit by making the AllowJsonGetAttribute applicable to mvc-controllers (not just individual action-methods):

using System.Web.Mvc;
public sealed class AllowJsonGetAttribute : ActionFilterAttribute, IActionFilter
{
    void IActionFilter.OnActionExecuted(ActionExecutedContext context)
    {
        var jsonResult = context.Result as JsonResult;
        if (jsonResult == null) return;

        jsonResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
    }

    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        var jsonResult = filterContext.Result as JsonResult;
        if (jsonResult == null) return;

        jsonResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
        base.OnResultExecuting(filterContext);
    }
}
+20

You do not need it.

If your action has the HttpPost attribute, then you do not need to bother with setting the JsonRequestBehavior and use the overload without it. There is an overload for each method without the JsonRequestBehavior enum. Here they are:

Without JsonRequestBehavior

protected internal JsonResult Json(object data);
protected internal JsonResult Json(object data, string contentType);
protected internal virtual JsonResult Json(object data, string contentType, Encoding contentEncoding);

With JsonRequestBehavior

protected internal JsonResult Json(object data, JsonRequestBehavior behavior);
protected internal JsonResult Json(object data, string contentType, 
                                   JsonRequestBehavior behavior);
protected internal virtual JsonResult Json(object data, string contentType, 
    Encoding contentEncoding, JsonRequestBehavior behavior);
0
votes
answers
18 views
+10

Could you explain STA and MTA?

Can you explain STA and MTA in your own words?

Also, what are apartment threads and do they pertain only to COM? If so, why?

0
votes
answers
30 views
+10

搜索特定列中的數字範圍並隱藏不在範圍內的行

-1

我想要搜索表格的某一列,查找不帶數據表插件的數字範圍並使用jquery或javascript。
用於最小值的文本框和用於最大值的文本框。搜索特定列中的數字範圍並隱藏不在範圍內的行

我有一個簡單的搜索某些列,但我不知道如何使它搜索範圍。

的javascript:

function SFNAAB_Code() { 

    var input, filter, table, tr, td, i; 
    input = document.getElementById("SFNAAB_CodeInput"); 
    filter = input.value.toUpperCase(); 
    table = document.getElementById("myTable"); 
    tr = table.getElementsByTagName("tr"); 

    for (i = 0; i < tr.length; i++) { 
     td = tr[i].getElementsByTagName("td")[1]; 
     if (td) { 
      if (td.innerHTML.toUpperCase().indexOf(filter) > -1) { 
       tr[i].style.display = ""; 
      } else { 
       tr[i].style.display = "none"; 
      } 
     } 
    } 
} 

HTML:

<input type="text" id="SFNAAB_CodeInput" onkeyup="SFNAAB_Code()" 
placeholder="Search By NAAB Code..."> 

<table id="myTable"> 
    <thead> 
    <tr> 
     <th> 
      @Html.DisplayNameFor(model => model.RegNo) 
     </th> 
     <th> 
      @Html.DisplayNameFor(model => model.NAAB_CODE) 
     </th> 
     <th> 
      @Html.DisplayNameFor(model => model.NAME) 
     </th> 
     <th> 
      @Html.DisplayNameFor(model => model.ICC) 
     </th> 
    </tr> 
    </thead> 
    <tbody> 
    @foreach (var item in Model) 
    { 
     <tr> 
      <td> 
       @Html.DisplayFor(modelItem => item.RegNo) 
      </td> 
      <td> 
       @Html.DisplayFor(modelItem => item.NAAB_CODE) 
      </td> 
      <td> 
       @Html.DisplayFor(modelItem => item.NAME) 
      </td> 
      <td> 
       @Html.DisplayFor(modelItem => item.ICC) 
      </td> 
     </tr> 
    } 
     </tbody> 
    </table> 
+0

我認爲你將不得不爲每個列TD進行搜索,然後或在您若檢查 – dementis

+0

你是說你每個條件要'td.innerHTML .toUpperCase()。indexOf(filter)> -1'是範圍檢查而不是存在檢查? – Taplar

+0

@Taplar是! ,我如何改變它有兩個文本框的最小值和最大值? –

沙发
0
0

解決它使用範圍的搜索數據表插件使用這些選項:

var table = $('#myTable').DataTable({ 
     paging: false, 
     info: false 
    }); 

,並移除了sDOM的F。
繼承人的代碼:

$.fn.dataTable.ext.search.push(
function(settings, data, dataIndex) { 
    var min = parseInt($('#min').val(), 10); 
    var max = parseInt($('#max').val(), 10); 
    var age = parseFloat(data[3]) || 0; 

    if ((isNaN(min) && isNaN(max)) || 
     (isNaN(min) && age <= max) || 
     (min <= age && isNaN(max)) || 
     (min <= age && age <= max)) 
    { 
     return true; 
    } 
    return false; 
} 
); 

$(document).ready(function() { 
var table = $('#example').DataTable({ 
    paging: false, 
    info: false 
}); 

$('#min, #max').keyup(function() { 
    table.draw(); 
}); 
}); 

datatables Custom filtering - range search

0
votes
answers
36 views
+10

I/O異常:收到致命警報:protocol_version - Coldfusion + Authorize.net

1

我的服務器安裝了ColdFusion 10。我收到以下錯誤,當我測試我的服務器上Authorize.net支付:I/O異常:收到致命警報:protocol_version - Coldfusion + Authorize.net

I/O Exception: Received fatal alert: protocol_version 

這裏是CFHTTP請求:

<cfhttp method="Post" url="https://test.authorize.net/gateway/transact.dll" result="test"> 
    //Passed params here 
</cfhttp> 

貌似這個錯誤是由於一個SSL andshake_failure。調試並解決此問題。我跟着this tutorial將我的證書添加到我的密鑰庫。

這裏是ColdFusion的-out.log細節吧:

AM Information [ajp-bio-8012-exec-6] - Starting HTTP request {URL='https://test.authorize.net:443/gateway/transact.dll', method='Post'} 
Ignoring unavailable cipher suite: TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA 
Ignoring unavailable cipher suite: TLS_DHE_RSA_WITH_AES_256_CBC_SHA 
Ignoring unavailable cipher suite: TLS_ECDH_RSA_WITH_AES_256_CBC_SHA 
Ignoring unsupported cipher suite: TLS_DHE_DSS_WITH_AES_128_CBC_SHA256 
Ignoring unsupported cipher suite: TLS_DHE_DSS_WITH_AES_256_CBC_SHA256 
Ignoring unsupported cipher suite: TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 
Ignoring unsupported cipher suite: TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 
Ignoring unsupported cipher suite: TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 
Ignoring unsupported cipher suite: TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 
Ignoring unsupported cipher suite: TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 
Ignoring unsupported cipher suite: TLS_RSA_WITH_AES_256_CBC_SHA256 
Ignoring unavailable cipher suite: TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA 
Ignoring unsupported cipher suite: TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 
Ignoring unsupported cipher suite: TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 
Ignoring unavailable cipher suite: TLS_DHE_DSS_WITH_AES_256_CBC_SHA 
Ignoring unsupported cipher suite: TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 
Ignoring unsupported cipher suite: TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 
Ignoring unsupported cipher suite: TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 
Ignoring unavailable cipher suite: TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA 
Ignoring unavailable cipher suite: TLS_RSA_WITH_AES_256_CBC_SHA 
Ignoring unsupported cipher suite: TLS_RSA_WITH_AES_128_CBC_SHA256 
Allow unsafe renegotiation: false 
Allow legacy hello messages: true 
Is initial handshake: true 
Is secure renegotiation: false 
%% No cached client session 
*** ClientHello, TLSv1 
RandomCookie: GMT: 1511005047 bytes = { 67, 167, 50, 23, 163, 143, 93, 78, 34, 130, 190, 65, 198, 95, 171, 222, 138, 10, 186, 140, 135, 200, 81, 223, 162, 61, 12, 196 } 
Session ID: {} 
Cipher Suites: [TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_DSS_WITH_AES_128_CBC_SHA, TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_RSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA, TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA, SSL_RSA_WITH_RC4_128_SHA, TLS_ECDH_ECDSA_WITH_RC4_128_SHA, TLS_ECDH_RSA_WITH_RC4_128_SHA, SSL_RSA_WITH_RC4_128_MD5, TLS_EMPTY_RENEGOTIATION_INFO_SCSV] 
Compression Methods: { 0 } 
Extension elliptic_curves, curve names: {secp256r1, sect163k1, sect163r2, secp192r1, secp224r1, sect233k1, sect233r1, sect283k1, sect283r1, secp384r1, sect409k1, sect409r1, secp521r1, sect571k1, sect571r1, secp160k1, secp160r1, secp160r2, sect163r1, secp192k1, sect193r1, sect193r2, secp224k1, sect239k1, secp256k1} 
Extension ec_point_formats, formats: [uncompressed] 
Extension server_name, server_name: [host_name: test.authorize.net] 
*** 
[write] MD5 and SHA1 hashes: len = 176 
0000: 01 00 00 AC 03 01 5A 10 1B 77 43 A7 32 17 A3 8F ......Z..wC.2... 
0010: 5D 4E 22 82 BE 41 C6 5F AB DE 8A 0A BA 8C 87 C8 ]N"..A._........ 
0020: 51 DF A2 3D 0C C4 00 00 2A C0 09 C0 13 00 2F C0 Q..=....*...../. 
0030: 04 C0 0E 00 33 00 32 C0 08 C0 12 00 0A C0 03 C0 ....3.2......... 
0040: 0D 00 16 00 13 C0 07 C0 11 00 05 C0 02 C0 0C 00 ................ 
0050: 04 00 FF 01 00 00 59 00 0A 00 34 00 32 00 17 00 ......Y...4.2... 
0060: 01 00 03 00 13 00 15 00 06 00 07 00 09 00 0A 00 ................ 
0070: 18 00 0B 00 0C 00 19 00 0D 00 0E 00 0F 00 10 00 ................ 
0080: 11 00 02 00 12 00 04 00 05 00 14 00 08 00 16 00 ................ 
0090: 0B 00 02 01 00 00 00 00 17 00 15 00 00 12 74 65 ..............te 
00A0: 73 74 2E 61 75 74 68 6F 72 69 7A 65 2E 6E 65 74 st.authorize.net 
ajp-bio-8012-exec-6, WRITE: TLSv1 Handshake, length = 176 
[Raw write]: length = 181 
0000: 16 03 01 00 B0 01 00 00 AC 03 01 5A 10 1B 77 43 ...........Z..wC 
0010: A7 32 17 A3 8F 5D 4E 22 82 BE 41 C6 5F AB DE 8A .2...]N"..A._... 
0020: 0A BA 8C 87 C8 51 DF A2 3D 0C C4 00 00 2A C0 09 .....Q..=....*.. 
0030: C0 13 00 2F C0 04 C0 0E 00 33 00 32 C0 08 C0 12 .../.....3.2.... 
0040: 00 0A C0 03 C0 0D 00 16 00 13 C0 07 C0 11 00 05 ................ 
0050: C0 02 C0 0C 00 04 00 FF 01 00 00 59 00 0A 00 34 ...........Y...4 
0060: 00 32 00 17 00 01 00 03 00 13 00 15 00 06 00 07 .2.............. 
0070: 00 09 00 0A 00 18 00 0B 00 0C 00 19 00 0D 00 0E ................ 
0080: 00 0F 00 10 00 11 00 02 00 12 00 04 00 05 00 14 ................ 
0090: 00 08 00 16 00 0B 00 02 01 00 00 00 00 17 00 15 ................ 
00A0: 00 00 12 74 65 73 74 2E 61 75 74 68 6F 72 69 7A ...test.authoriz 
00B0: 65 2E 6E 65 74          e.net 
[Raw read]: length = 5 
0000: 15 03 01 00 02          ..... 
[Raw read]: length = 2 
0000: 02 46            .F 
ajp-bio-8012-exec-6, READ: TLSv1 Alert, length = 2 
ajp-bio-8012-exec-6, RECV TLSv1 ALERT: fatal, protocol_version 
ajp-bio-8012-exec-6, called closeSocket() 
ajp-bio-8012-exec-6, handling exception: javax.net.ssl.SSLException: Received fatal alert: protocol_version 
Finalizer, called close() 
Finalizer, called closeInternal(true) 

添加認證後,我還是收到了同樣的錯誤。然後,我在jvm.config中添加了以下幾行:

-Djavax.net.ssl.keyStore=C:\ColdFusion10\jre\lib\security\cacerts 
-Djavax.net.ssl.keyStorePassword=password 
-Djavax.net.ssl=debug 
-Djavax.net.debug=all 

我仍然遇到同樣的錯誤。

還有一個想法是,Authorize.net需要TLS 1.2來處理它們的API請求。我目前在CF 10上使用Java 1.7。我是否需要將我的Java版本升級到1.8才能提出請求?任何人都可以幫我解決這個問題嗎?

沙发
0
0

我已將JAVA版本升級到1.8版本,問題得到解決。

0
votes
answers
40 views
+10

Asp.NET Webforms register.aspx驗證

-1

我正在開發一個使用Visual Studio 2017的自定義網站。我已經包含了Identity,因此有一些提供的頁面用於註冊或登錄用戶。我正在修改註冊頁面以允許使用fileupload控件上傳圖片(我創建了一個配置文件表,這將保存我想要捕獲的額外數據)。但是,當我這樣做時,即使電子郵件文本框中有數據,我提交時也會觸發電子郵件驗證。我認爲這可能與上傳功能發生時頁面重新加載的方式有關?我還想添加一個複選框並顯示其他字段(如果選中),使用CheckedChanged事件來設置我想要隱藏的控件的Visible屬性。我已經看到,如果我想這樣做,我需要將AutoPostBack設置爲true。 代碼在register.aspxAsp.NET Webforms register.aspx驗證

<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent"> 
    <h2><%: Title %>.</h2> 
    <p class="text-danger"> 
     <asp:Literal runat="server" ID="ErrorMessage" /> 
    </p> 

    <div class="form-horizontal"> 
     <h4>Create a new account</h4> 
     <hr /> 
     <asp:ValidationSummary runat="server" CssClass="text-danger" /> 
     <div class="form-group"> 
      <asp:Label runat="server" AssociatedControlID="UserName" CssClass="col-md-2 control-label">User Name</asp:Label> 
      <div class="col-md-10"> 
       <asp:TextBox runat="server" ID="UserName" CssClass="form-control" /> 
       <asp:RequiredFieldValidator runat="server" ControlToValidate="UserName" 
        CssClass="text-danger" ErrorMessage="The user name is required." /> 
      </div> 
     </div> 
     <div class="form-group"> 
      <asp:Label runat="server" AssociatedControlID="Email" CssClass="col-md-2 control-label">Email</asp:Label> 
      <div class="col-md-10"> 
       <asp:TextBox runat="server" ID="Email" CssClass="form-control" TextMode="Email" /> 
       <asp:RequiredFieldValidator runat="server" ControlToValidate="Email" 
        CssClass="text-danger" ErrorMessage="The email field is required." /> 
      </div> 
     </div> 
     <div class="form-group"> 
      <asp:Label runat="server" AssociatedControlID="Password" CssClass="col-md-2 control-label">Password</asp:Label> 
      <div class="col-md-10"> 
       <asp:TextBox runat="server" ID="Password" TextMode="Password" CssClass="form-control" /> 
       <asp:RequiredFieldValidator runat="server" ControlToValidate="Password" 
        CssClass="text-danger" ErrorMessage="The password field is required." /> 
      </div> 
     </div> 
     <div class="form-group"> 
      <asp:Label runat="server" AssociatedControlID="ConfirmPassword" CssClass="col-md-2 control-label">Confirm password</asp:Label> 
      <div class="col-md-10"> 
       <asp:TextBox runat="server" ID="ConfirmPassword" TextMode="Password" CssClass="form-control" /> 
       <asp:RequiredFieldValidator runat="server" ControlToValidate="ConfirmPassword" 
        CssClass="text-danger" Display="Dynamic" ErrorMessage="The confirm password field is required." /> 
       <asp:CompareValidator runat="server" ControlToCompare="Password" ControlToValidate="ConfirmPassword" 
        CssClass="text-danger" Display="Dynamic" ErrorMessage="The password and confirmation password do not match." /> 
      </div> 
     </div> 
     <div class="form-group"> 
      <asp:Label runat="server" AssociatedControlID="UserPicture" CssClass="col-md-2 control-label">Upload your user picture</asp:Label> 
      <div class="col-md-10"> 
       <asp:FileUpload runat="server" ID="UserPicture" CssClass="form-control" /> 
      </div> 
     </div> 

     <div class="form-group"> 
      <asp:Label runat="server" AssociatedControlID="userStatus" CssClass="col-md-2 control-label">Do you want to upload Artwork? If so check this box and once approved you will be able to do this.</asp:Label> 
      <div class="col-md-10"> 
       <asp:CheckBox ID="userStatus" runat="server" CssClass="form-control" AutoPostBack="true" Checked=false OnCheckedChanged="userStatus_CheckedChanged" /> 
      </div> 
     </div> 
     <div class="form-group"> 
      <asp:Label runat="server" AssociatedControlID="ArtistIntro" CssClass="col-md-2 control-label" ID="lblInfo" Visible="True">Please enter information about yourself as an artist</asp:Label> 
      <div class="col-md-10"> 
       <asp:TextBox runat="server" ID="ArtistIntro" CssClass="form-control" Visible="True" /> 
      </div> 
     </div> 
     <div class="form-group"> 
      <div class="col-md-offset-2 col-md-10"> 
       <asp:Button runat="server" OnClick="CreateUser_Click" Text="Register" CssClass="btn btn-default" /> 
       <asp:Label ID="lblError" runat="server"></asp:Label> 
      </div> 
     </div> 
    </div> 
</asp:Content> 

在register.aspx.cs

using System; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using Microsoft.AspNet.Identity; 
using Microsoft.AspNet.Identity.Owin; 
using Owin; 
using UHFinal.Models; 
using System.Data.SqlClient; 

namespace UHFinal.Account 
{ 
    public partial class Register : Page 
    { 
     protected void CreateUser_Click(object sender, EventArgs e) 
     { 
      var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>(); 
      var signInManager = Context.GetOwinContext().Get<ApplicationSignInManager>(); 
      var user = new ApplicationUser() { UserName = UserName.Text }; 
      IdentityResult result = manager.Create(user, Password.Text); 
      if (result.Succeeded) 
      { 

       //Insert a UserAccount record to save the additional details. 
       //Also sets the userStatus. AP or UP, Artist Pending or User Pending 

       string connStr = System.Configuration.ConfigurationManager.ConnectionStrings["defaultConnection"].ConnectionString; 
       SqlConnection conn = new SqlConnection(connStr); 
       SqlCommand insert = new SqlCommand("insert into userAccount(UserID, userStatus, UserPicture, ArtistIntro) " + 
        "values(@userId, @userStatus, @UserPicture, @UserIntro)", conn); 
       insert.Parameters.AddWithValue("@userId", user.Id); 
       if (userStatus.Checked == true) { 
        insert.Parameters.AddWithValue("@userStatus", "AP"); 
        } 
       else 
       { 
        insert.Parameters.AddWithValue("@userStatus", "UP"); 
       } 
       insert.Parameters.AddWithValue("@UserPicture", "UserPics/" + UserPicture.FileName); 
       insert.Parameters.AddWithValue("@UserIntro", ArtistIntro.Text); 

       try 
       { 
        conn.Open(); 
        object returnObj = insert.ExecuteNonQuery(); 
       } 
       catch (Exception ex) 
       { 
        lblError.Text = "Error: " + ex.Message;  
       } 
       conn.Close(); 


       signInManager.SignIn(user, isPersistent: false, rememberBrowser: false); 
       IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); 

       } 

      else 
      { 
       ErrorMessage.Text = result.Errors.FirstOrDefault(); 
      } 
     } 

     protected void userStatus_CheckedChanged(object sender, EventArgs e) 
     { 
      if (userStatus.Checked == true) 
      { 
       ArtistIntro.Visible = true; 
       lblInfo.Visible = true; 
      } 
      else 
      { 
       ArtistIntro.Visible = false; 
       lblInfo.Visible = false; 
      } 
     } 
    } 
} 
+0

請顯示您的代碼。 –

+0

抱歉,它大部分是由Visual Studio生成的。 –

沙发
0
0

排序的代碼,創建新ApplicationUser當我剛走出去的電子郵件。

var user = new ApplicationUser() { UserName = UserName.Text, Email = Email.Text }; 
0
votes
answers
41 views
+10

如何使用從Api控制器中的GET方法返回的IEnumerable填充DropDownList?

0

我是MVC中的web應用程序的新手。在過去的兩天裏,我研究並嘗試了很多東西,但沒有一個適用於我;我使用ApiController,而不是控制器,所以我不能做像「返回視圖(模型)」的東西。如何使用從Api控制器中的GET方法返回的IEnumerable填充DropDownList?

如果你能幫助我理解如何將這些東西連接在一起或顯示我的問題在哪裏將非常感謝!

情況: 我想製作一個具有級聯下拉列表的網絡應用程序;第一個選擇汽車製造商名單,第二個名單顯示所選製造商的汽車型號。列表和提交按鈕將在AJAX表單中。

問題: 我只是想知道,我怎麼能填充第一個下拉頁面加載列表,用我的ApiController一個GET方法返回的汽車製造一個IEnumerable? 然後我可以從那裏去。請記住,稍後我將有第二個下拉列表根據第一個下拉列表填充/更新,因此我希望下拉列表的填充位置在客戶端完成。

我試了一下:

  1. 使用HTML.DropDownListFor創建列表,但 HTML.DropDownListFor總是得到「未將對象引用設置到對象的實例 」。我也使用Ajax.BeginForm,但不知道 是否可以實際調用返回IEnumerable的GET方法,並將其添加到 列表中。
  2. 使用$(document).ready()來使用getJSON來獲取從我的 ApiController方法獲得的汽車,但getJSON不會觸發。

我可能在某個地方發生了很大的錯誤,因爲我無法獲得任何東西來填充我的列表,而且我仍在學習。非常感謝您的幫助!我現在將顯示我的代碼,以及我嘗試過的一些替代代碼。


首先是我的模型類:

public class Make 
    { 
     public int MakeId { get; set; } 
     public string MakeName { get; set; } 
    } 

    public class Model 
    { 
     public int ModelId { get; set; } 
     public string ModelName { get; set; } 
     public int MakeId { get; set; } 
    } 

    public class MakeViewModel 
    { 
     public int SelectedMakeId { get; set; } 
     public IEnumerable<Make> MakesList { get; set; } 
    } 

這裏是我的兩個GET方法,使()和模式(INT makeID),每個返回IEnumerable的車輛ApiController。他們最終會從本地xml中消費,但現在爲了簡單起見,我將其刪除,每個只返回一個Make或Model項目的列表。

public class VehicleController : ApiController 
{ 
    [System.Web.Http.HttpGet] 
    public IEnumerable<Make> Makes() 
    { 
     List<Make> makesList = new List<Make>(); 

     //Code for consuming from xml file will go here 

     //For now, add one test make to the list 
     Make maketest = new Make(); 
     maketest.MakeId = 1; 
     maketest.MakeName = "MakeTest"; 
     makesList.Add(maketest); 

     //return List of the one test make 
     return makesList; 
    } 

    [System.Web.Http.HttpGet] 
    public IEnumerable<Model> Models(int id) 
    { 
     List<Model> modelsList = new List<Model>(); 

     //Code for consuming from xml file will go here 

     //For now, add one test model to the list 
     Model modeltest = new Model(); 
     modeltest.ModelId = 1; 
     modeltest.ModelName = "ModelTest"; 
     modeltest.MakeId = 1; 
     modelsList.Add(modeltest); 

     //return List of the one test model 
     return modelsList; 
    } 
} 

這是我的Index.cshtml,它加載_Form.cshtml

<h2>Vehicle Selector</h2> 
@{ 
    ViewBag.Title = "Home Page"; 
    @Html.Partial("_Form"); 
} 

最後是我的局部視圖_Form.cshtml的局部視圖;我將只顯示第一個下拉列表的文件的前半部分。 在頂部,包括我的模型MakeViewModel這是我們可以找到我們的車的名單,使..

@model VehicleMVC.Models.MakeViewModel 
<script src="@Url.Content("~/Scripts/jquery-1.10.2.min.js")" 
    type="text/javascript"></script> 
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" 
    type="text/javascript"></script> 

我用Ajax.BeginForm()調用GET方法使()從我VehicleController更新我的makes_DDL,因爲我希望頁面加載時填充列表。老實說問題可能在這裏,因爲我不確定它是正確的。

@using (Ajax.BeginForm("Makes", "Vehicle", new AjaxOptions 
    { 
     HttpMethod = "GET", 
     UpdateTargetId = "makes_DDL" 
    })) 

我用Html.DropDownListFor()創建makes_DDL列表,雖然它總是給我的錯誤「不設置到對象的實例對象引用」。

@Html.DropDownListFor(model => model.SelectedMakeId, 
    (SelectList)Model.MakesList, new { @class = "makes_DDL" }) 

非常感謝你提前!


有些事情我想: 我嘗試使用新的SelectList,但沒有運氣:

@Html.DropDownListFor(model => model.SelectedMakeId, new 
    SelectList(Model.MakesList, "MakeId", "MakeName")) 

然後我試圖硬編碼品牌的測試列表,但相同的「對象未設置到一個對象的實例「錯誤。

@Html.DropDownListFor(model => model.SelectedMakeId, 
    new SelectList(new List<VehicleMVC.Models.Make> 
    { 
     new VehicleMVC.Models.Make { MakeId = 0, MakeName = "SmallCar"}, 
     new VehicleMVC.Models.Make { MakeId = 1, MakeName = "BigCar"} 
    }, 
    "value", "text", 0), new { @class = "makes_DDL" }) 

既然我敢肯定的是,Ajax.BeginForm沒有做我想要的(從我VehicleController調用get使得()方法來填充makes_DDL列表)是什麼,我試圖用$(文件)。就緒()使用getJSON來使用應該調用Makes()的路由「api/vehicle」,但它似乎不會觸發getJSON,因爲我放入的警報不會觸發。

<script type="text/javascript"> 
    function getMakes() { 
     $.getJSON("api/vehicle", 
      function (data) { 
       //This alert doesn't fire, so it seems getJSON is not firing?    
       window.alert(1); 
       //Code would later go here for appending the makes from the 
        returned IEnumerable to the makes_DDL list 
      }); 
    } 

$(document).ready(getMakes); 
</script> 
+0

你爲什麼不能填充你的第一個下拉列表中的內容在你的MVC操作方法,使您的看法?您正在獲取空引用異常,因爲「Model.MakesList」可能爲空。或'Model'可能爲空。您尚未分享GET操作的外觀。 – Shyju

+0

建議你看看[這個DotNetFiddle](https://dotnetfiddle.net/1bPZym)中的代碼 - 它的MVC,但應該給你的基本綱要 –

+0

拍攝,我認爲你是對的。我只是意識到我似乎沒有任何實際將製作放入我的MakesViewModel中的MakesList中的任何東西。我記得其他人使用Controller類而不是ApiController似乎做了類似「return View(obj)」的事情。 能否詳細介紹一下我將如何將從我的VehicleController中的方法返回的汽車的IEnumerable存儲到我的Model(我的MakeViewModel類中的MakesList)中?我很困惑,因爲它似乎不應該使用像ActionResult Index()這樣的東西。 謝謝你的回覆! –

沙发
0
0

而不是使用@Html.DropDownListFor可以使用<select>標籤如下,

<select id="SelectedMakeId" name="SelectedMakeId"></select> 

然後你就可以用getJson

$(document).ready(function (e) { 
    $.getJSON("http://localhost:2390/api/vehicle", function (data) { 
     $.each(data, function (index, value) { 
      $("#SelectedMakeId").append("<option value=" + value.MakeId + ">" + value.MakeName + "</option>"); 
     }); 
    }); 
}); 

請注意,你必須給正確的API方法填充它網址。而不是給這個網址http://localhost:2390/api/vehicle你必須給你的路徑。

你可以嘗試這其中也

您可以使用ViewBag爲好。對於做到以下幾點,

1.設置路線API方法Makes()

 [System.Web.Http.Route("api/Vehicle/MakersList")] 
    [System.Web.Http.HttpGet] 
    public IEnumerable<Make> Makes() 
    { 
     ... 
    } 

2.更改Index方法

添加GetMakers()方法消耗API方法。使用此GetMakers()初始化ViewBag.listMakers

 private string MAKER_URL = "http://localhost:2390/api/vehicle"; 
    public ActionResult Index() 
    { 
      ViewBag.listMakers = new SelectList(GetMakers(), "MakeId","MakeName"); 
      return View(); 
    } 

    public IEnumerable<Make> GetMakers() 
    { 
     try 
      { 
       HttpClient client = new HttpClient(); 
       client.BaseAddress = new Uri(MAKER_URL); 
       client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 
       HttpResponseMessage response = client.GetAsync("vehicle/MakersList").Result; 
       if (response.IsSuccessStatusCode) 
        return response.Content.ReadAsAsync<IEnumerable<Make>>().Result; 
       return null; 
      } 
      catch 
      { 
       return null; 
      } 

    } 

3.改寫@Html.DropDownListFor

@Html.DropDownListFor(model => model.SelectedMakeId, (IEnumerable<SelectListItem>)ViewBag.listMakers, "---Select---", new { @class = "makes_DDL" }) 
+0

噢謝謝你的回覆!我創建了第二個類似的列表,但沒有想到只是完全刪除Html.DropDownListFor並且還使用getJSON作爲第一個列表。謝謝,我會試試看! –

+0

@YoshiKirishima查看最新的答案.. –

+0

再次感謝你!我將探索這兩種選擇。第一個對我來說效果不錯!我的getJSON遇到問題,因爲我認爲我應該遵循RouteConfig中的路由URL,而不是WebApiConfig中的URL。一旦我使用地址API /車輛/而不是API /車輛,它的工作! –

0
votes
answers
18 views
+10

允許全局熱鍵

1

首先,我不是一個真正的編碼器,但我很滿意迄今爲止所做的。允許全局熱鍵

我已經寫下了這個代碼,這是與機器人技術。下面的代碼允許我在單擊表單時使用鍵盤快捷鍵。但是,無論應用程序是否處於焦點或甚至最小化狀態,我都需要使用熱鍵。

我已經看了網上,但它不是很清楚。

Public Class MainForm 

    Private Sub MainForm_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown 

     If (e.KeyCode And Not Keys.Modifiers) = Keys.T AndAlso e.Modifiers = Keys.Control Then 
      DF1Com1.Write("O:1/0", "1") ' (O:9/0) (R) 
     End If 

     'If e.KeyCode = Keys.R Then 
     'DF1Com1.Write("O:1/0", "1") ' (O:9/0) (R) 
     'End If 

    End Sub 

    Private Sub MainForm_KeyUp(sender As Object, e As KeyEventArgs) Handles Me.KeyUp 

     If (e.KeyCode And Not Keys.Modifiers) = Keys.T AndAlso e.Modifiers = Keys.Control Then 
      DF1Com1.Write("O:1/0", "0") ' (O:9/0) (R) 
     End If 

     'If e.KeyCode = Keys.R Then 
     'DF1Com1.Write("O:1/0", "0") ' (O:9/0) (R) 
     'End If 

    End Sub 

Public Class MainForm 


    Private Sub MainForm_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown 

     If (e.KeyCode And Not Keys.Modifiers) = Keys.T AndAlso e.Modifiers = Keys.Control Then 
      DF1Com1.Write("O:1/0", "1") ' (O:9/0) (R) 
     End If 

     'If e.KeyCode = Keys.R Then 
     'DF1Com1.Write("O:1/0", "1") ' (O:9/0) (R) 
     'End If 

    End Sub 

    Private Sub MainForm_KeyUp(sender As Object, e As KeyEventArgs) Handles Me.KeyUp 

     If (e.KeyCode And Not Keys.Modifiers) = Keys.T AndAlso e.Modifiers = Keys.Control Then 
      DF1Com1.Write("O:1/0", "0") ' (O:9/0) (R) 
     End If 

     'If e.KeyCode = Keys.R Then 
     'DF1Com1.Write("O:1/0", "0") ' (O:9/0) (R) 
     'End If 

    End Sub 

End Class 

更新:

權。我已經添加了一個允許註冊GlobalKey的類。

在我的主要形式,我現在有這個鍵:

Public Class MainForm 
    Dim hkr As New HotKeyRegistryClass(Me.Handle) 

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 
     hkr.Register(HotKeyRegistryClass.Modifiers.MOD_CTRL, Keys.A).ToString() 
     hkr.Register(HotKeyRegistryClass.Modifiers.MOD_CTRL, Keys.S).ToString() 
     hkr.Register(HotKeyRegistryClass.Modifiers.MOD_CTRL, Keys.D).ToString() 
     hkr.Register(HotKeyRegistryClass.Modifiers.MOD_CTRL, Keys.F).ToString() 
     hkr.Register(HotKeyRegistryClass.Modifiers.MOD_CTRL, Keys.G).ToString() 
     hkr.Register(HotKeyRegistryClass.Modifiers.MOD_SHIFT Or HotKeyRegistryClass.Modifiers.MOD_CTRL, Keys.H).ToString() 
    End Sub 

    Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message) 
     If m.Msg = HotKeyRegistryClass.Messages.WM_HOTKEY Then 'NOT THE ACTUAL WINDOWS NAMESPACE 
      Dim ID As String = m.WParam.ToString() 
      Select Case ID 
       Case 0 : If DF1Com1.Write("O:1/0", "1") Then DF1Com1.Write("O:1/0", "0") 
       Case 1 : MessageBox.Show("S") 
       Case 2 : MessageBox.Show("D") 
       Case 3 : MessageBox.Show("F") 
       Case 4 : MessageBox.Show("G") 
       Case 5 : MessageBox.Show("H") 
      End Select 
     End If 
     MyBase.WndProc(m) 
    End Sub 

如果你看看案例0。它可以工作,但它不會使鑰匙備份。它一直壓下來。我需要它的時候,關鍵是鬱悶它DF1Com1.Write( 「O:1/0」, 「0」)'

類代碼

Public NotInheritable Class HotKeyRegistryClass 
    Private Declare Function RegisterHotKey Lib "user32.dll" (ByVal handle As IntPtr, ByVal id As Int32, ByVal fsModifier As Int32, ByVal vk As Int32) As Int32 
    Private Declare Function UnregisterHotKey Lib "user32.dll" (ByVal handle As IntPtr, ByVal id As Int32) As Int32 
    Private Handle As IntPtr = IntPtr.Zero 
    Private Registry As New System.Collections.Generic.List(Of Int32) 
    Public Enum Messages 
     [WM_HOTKEY] = &H312 
    End Enum 
    Public Enum Modifiers 
     [MOD_ALT] = &H1 
     [MOD_CTRL] = &H2 
     [MOD_SHIFT] = &H4 
    End Enum 
    Sub New(ByVal Handle As IntPtr) 
     Me.Handle = Handle 
    End Sub 
    Public Function Register(ByVal Modifier As Int32, ByVal Key As System.Windows.Forms.Keys) As Int32 
     Dim ret As Int32 
     ret = NextAvailableIndex() 
     Call RegisterHotKey(Me.Handle, ret, Modifier, Key) 
     Registry.Insert(ret, ret) 
     Return ret 
    End Function 
    Public Sub Unregister(ByVal ID As Int32) 
     Call UnregisterHotKey(Me.Handle, ID) 
     Registry.Remove(ID) 
    End Sub 
    Private Function NextAvailableIndex() As Int32 
     Dim ret As Int32 = 0 
     Dim n As Int32 = 0 
     For i As Int32 = 0 To Registry.Count - 1 
      If Registry(i) = n Then 
       n = n + 1 
      ElseIf n < Registry(i) Then 
       Return n 
      End If 
     Next 
     If n = Registry.Count Then 
      Return Registry.Count 
     End If 
     Return ret 
    End Function 
End Class 
+1

查看'Windows.Input.Keyboard.GetKeyStates',而不是捕獲窗體上的關鍵事件,輪詢計時器或後臺線程中的鍵狀態。 –

+1

問這個問題。有點不公正。正如我所說的。我不是一個硬核編碼器。 – Arthor

+1

我已經更新了代碼,我幾乎是他們的。仍在繼續,但我堅持最後一部分。 – Arthor

沙发
0
1

遺憾的是,只有RegisterHotkey告訴你當一個組合鍵被激活時。另外,正如您已經意識到的那樣,只有當您的應用具有焦點時,您才能使用KeyDownKeyUp事件。

真正全球化的KeyDownKeyUp的唯一方法是使用低級別的鍵盤鉤子。由於我不想複製我的整個答案,我只會鏈接到它。該鏈接將爲您設置鍵盤掛鉤提供一些指導。

How to disable/override Windows 10 Hotkeys with C#

另一種可能性是在熱鍵激活這樣執行這兩個命令...

Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message) 
     If m.Msg = HotKeyRegistryClass.Messages.WM_HOTKEY Then 'NOT THE ACTUAL WINDOWS NAMESPACE 
      Dim ID As String = m.WParam.ToString() 
      Select Case ID 
       Case 0 : 
        DF1Com1.Write("O:1/0", "1") 
        System.Threading.Thread.Sleep(2000) 
        DF1Com1.Write("O:1/0", "0") 
       Case 1 : MessageBox.Show("S") 
       Case 2 : MessageBox.Show("D") 
       Case 3 : MessageBox.Show("F") 
       Case 4 : MessageBox.Show("G") 
       Case 5 : MessageBox.Show("H") 
      End Select 
     End If 
     MyBase.WndProc(m) 
    End Sub 
+0

只是一個簡單的問題。我知道你在C#中有你的解決方案。是否有一個VB.NET解決方案,因爲我的機器人系統使用VB.NET。和以前一樣,我不介意如果我不能進入最低級別,我只需要一種方法,一旦釋放了密鑰,就可以停用'DF1Com1.Write(「O:1/0」,「0」)。謝謝 – Arthor

+0

你應該可以從CodeProject中獲取項目並將C#編譯成DLL庫。然後,您可以引用該庫並在VB.net中編寫處理程序。 –

+0

也許....通過RegisterHotkey激活每個熱鍵應執行第一個代碼DF1Com1.Write(「O:1/0」,「1」),然後休眠一秒鐘然後執行最後一位, 'DF1Com1.Write(「O:1/0」,「0」)'。基本上這意味着即使您按住按鍵,每次按鍵也只能使機器人移動一定的量。如果這不起作用,那麼我只能想到一個鍵盤鉤子。 –

板凳
0
0

達到這個目的可能是使用布爾追蹤的另一種選擇。這意味着,按熱鍵啓動,然後再按一次停止。

Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message) 
Static toggle As Boolean 
     If m.Msg = HotKeyRegistryClass.Messages.WM_HOTKEY Then 'NOT THE ACTUAL WINDOWS NAMESPACE 
      Dim ID As String = m.WParam.ToString() 
      Select Case ID 
       Case 0 : 
      If toggle Then 
      DF1Com1.Write("O:1/0", "0") 
      Else 
         DF1Com1.Write("O:1/0", "1") 
      End If 
      toggle = Not toggle 
       Case 1 : MessageBox.Show("S") 
       Case 2 : MessageBox.Show("D") 
       Case 3 : MessageBox.Show("F") 
       Case 4 : MessageBox.Show("G") 
       Case 5 : MessageBox.Show("H") 
      End Select 
     End If 
     MyBase.WndProc(m) 
    End Sub 
+0

你好,好主意。但不幸的是,這樣做不可行。我只能想象會出錯的用戶數量。由於這個系統不只是由我自己使用, – Arthor

+0

你好,有人提議的解決方案的任何更新有一天提出。謝謝 – Arthor

+0

我已經取得了一些進展,但假期讓我感到耽擱。我會盡力在今天完成。 –